# Random Numbers in Objective-C

Posted by Jan Vantomme on 11 March 2009.

Tags: iphone, objective-c, random

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