Contribute  :  Calendar  :  Advanced Search  :  Site Statistics  :  Directory  :  Files to download  :  Links for developers  :  Privacy policy  :  Web Resources  :  Polls  
    MacOSX Guru Site Information, tips and tricks, FAQ for Mac OS X developers    
 Welcome to MacOSX Guru Site
 Monday, January 22 2018 @ 06:06 AM UTC

Random numbers

Objective-CHow 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 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)
And of course, most Math Department of Universities have pages about pseudo-random number generators...

What's Related

Story Options

Random numbers | 1 comments | Create New Account
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 UTC
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.

sincerely Mads E.
 Copyright © 2018 MacOSX Guru Site
 All trademarks and copyrights on this page are owned by their respective owners.
Powered By Geeklog 
Created this page in 0.06 seconds