Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

#1
June 15th, 2011, 03:36 AM
 ktoz
Contributing User

Join Date: Apr 2003
Posts: 562
Time spent in forums: 1 Week 5 Days 3 h 4 m 2 sec
Reputation Power: 69
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.

#2
June 16th, 2011, 05:05 AM
 ktoz
Contributing User

Join Date: Apr 2003
Posts: 562
Time spent in forums: 1 Week 5 Days 3 h 4 m 2 sec
Reputation Power: 69
[Solved]

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;

etc...

#3
May 8th, 2012, 08:20 PM
 b49P23TIvg
Contributing User

Join Date: Aug 2011
Posts: 3,360
Time spent in forums: 1 Month 2 Weeks 3 Days 9 h 55 m 30 sec
Reputation Power: 383
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
Code:
```number  probability
0         1/2
1         1/4
2         1/4```

Yes, so what is the best solution.
http://forums.devshed.com/c-programming-42/rand-code-to-simulate-rand-max-895833.html

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]Code tags[/code] are essential for python code!

 Viewing: Dev Shed Forums > Operating Systems > BSD Help > Using random() function for limited ranges