11 March 2009

Author

Jan Vantomme

Category

iPhone

Random Numbers in Objective-C

I was working on a simple particle system in Objective-C last weekend and I needed to generate random numbers between -1.0 and 1.0 for it. In Processing this is very easy: I just use random(-1.0, 1.0) and get the random number I want. I didn’t find a similar function in Objective-C so I tried writing my own.

Generating random numbers between zero and a positive number is easy. The following line of code generates a random number between 0 and 5.

float randomNum = (rand() / RAND_MAX) * 5;

To generate a random number between two positive numbers is a little trickier. This small piece of code generates a random number between 2 and 5.

// calculate difference between 5 and 2
float diff = 5 - 2;
// generate random number between 0 and 3
// add 2 to the random number
float randomNum = ((rand() / RAND_MAX) * diff) + 2;

I wrote a simple Foundation Tool to test the function. The program below prints 200 random numbers between -2.0 and 5.0 to the console.

randomFloatBetween function

float randomFloatBetween(float smallNumber, ¬
    float bigNumber)
{
    float diff = bigNumber - smallNumber;
    return (((float) rand() / RAND_MAX) * diff) ¬
        + smallNumber;
}

Main program

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool ¬
       alloc] init];
    int i;
    for (i = 1; i <= 200; i++) {
        float a = -2.0;
        float b = 5.0;
        float randomNumber1 = ¬ 
            randomFloatBetween(a, b);
        NSLog(@"Random Number between %f and %f: %f", ¬
            a, b, randomNumber1);
    }
    [pool drain];
    return 0;
}

Download the Example Project

Top · Tweet about this

Browse Articles

0 Opinions posted so far. Now go post your own. To the comment form!

Commenting is closed for this article.

Subscribe to this blog

About this blog

This is the personal weblog of Jan Vantomme.
I write about the everyday things that move me as a designer. I write shorter things on Twitter.

Add to Technorati Favorites

Some of the blogs I like

Andy Budd
Webdesign
Design Observer
Writings on Design and Culture
Design View
A blog on design by Andy Rutledge
Digital Web Magazine
The web professional's online magazine of choice
John Resig
John Resig on JavaScript and web development