#1
  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. #2
  3. 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...
  4. #3
  5. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,855
    Rep Power
    481
    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
    Code:
    number  probability
    0         1/2
    1         1/4
    2         1/4
    Yes, so what is the best solution.
    see thread
    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 and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo