# Random numbers

### Friday, January 02 2004 @ 12:02 AM GMT

**Contributed by: Mads**
How do I get evenly distributed numbers between 0 and 1 in Objective-C? The built-in random() function delivers the same number everytime you start your application.
A fine example to such a random number generator would be JavaSript's Math.Random(), but I don't know how that works
sincerely
Mads E.

To make random generate a different suite you need to call `srandom(unsigned long seed)`

with a different seed before using it. A common practice is to use the current time as seed.

To have random numbers between 0 and 1, you could trivially convert the result of `random()`

to double and divide it by `(double)0x7FFFFFFF`

, however if random returns an evenly distributed suite of number between 0 and 2^31-1, the conversion in floating point number and the division probably break the "evenly" nature of the suite , but it should satisfy most basic needs.

Here we posted a Xcode project with C++ code originally submitted to FlipCode.com on July 23, 2000 by John W. Ratcliff.

This code shows how to get a Gaussian suite of random numbers. We added the Objective C version of the same algorithm. Feel free to improve and, as usual, use at your own risk ;).

Some links about random number generators:

As often, "The Art of Computer programming" by D. Knuth, (Vol II, Chap. 3)

pLab

random.org

netlib

libranlib

And of course, most Math Department of Universities have pages about pseudo-random number generators...

1 comments

http://www.macosxguru.net/article.php?story=20031229194721194