### Thread: Using random() function for limited ranges

1. No Profile Picture
Contributing User
Devshed Novice (500 - 999 posts)

Join Date
Apr 2003
Posts
573
Rep Power
70

#### 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. No Profile Picture
Contributing User
Devshed Novice (500 - 999 posts)

Join Date
Apr 2003
Posts
573
Rep Power
70

#### [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...
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.