Friday, January 02 2004 @ 12:02 AM GMT
Contributed by: Mads
Views: 15,757
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...
The following comments are owned by whomever posted them. This site is not responsible for what they say.
Random numbers
Authored by: Mads on
Monday, January 05 2004 @ 09:18 PM GMT
Thanks!
This is certainly good enough for what I will use it for. I've
always been a little interested in how pseudo random generators
works, because a logical machine shouldn't be able to create
something as illogical as random numbers, so I will certainly also
find the llinks interesting. I wasn't used to random number
generators, that needed to be "seeded" but now I know how to
;-)
BTW I found [NSDate
timeIntervalSinceReferenceDate] useful for seeding.
BTW I found
[NSDate timeIntervalSinceReferenceDate]
useful for seeding.sincerely Mads E.