June 15th, 2011, 04:36 AM
Using random() function for limited ranges
I know this is an easy one, but the Mac man pages are completely devoid of examples and 1/2 hour of Googling produced not a single useful example of how to use the output from the random() function and clip it to specific number ranges. Every site mentioning it gets all carried away with the mathematics behind how it works and forgets to mention how mere mortals can use it to produce numbers between 0 and 26 or 0 and 100, or 0 and 1000 etc. How do you do it?
Thanks for any help.
June 16th, 2011, 06:05 AM
After playing around with various combinations, it did indeed turn out to be easy. For others who might need the solution, just do the following:
To get numbers between 0 and 25
random() % 25;
To get numbers between 0 and 100
random() % 100;
To get numbers between 0 and 1000
random() % 1000;
Your answer is incorrect. Look here--->
Suppose your maximum random number is 3.
You have a uniform distribution amongst 0, 1, 2, 3.
Now, we want a random number uniformly distributed from 0, 1, 2.
random() % 3 will generate numbers with probability
Yes, so what is the best solution.
Make sure that RAND_MAX+1 converted to double is different from RAND_MAX otherwise use extra logic to remove the case when RAND_MAX == random() .
[/code] are essential for python code and Makefiles!