Thread: Random Number

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

    Join Date
    Aug 2000
    Location
    Indiana
    Posts
    614
    Rep Power
    16
    For some reason random numbers don't seem to be that random in PHP (at least if the range like 2 numbers). It seems to favor the 1 instead of 2 about 90% of the time.

    Anybody know why this is, or how to work around it? (I'd like to have about a 50/50 split.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Aug 2000
    Location
    Indiana
    Posts
    614
    Rep Power
    16
    Nevermind. I forgot to seed the random number.
  4. #3
  5. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2000
    Location
    France
    Posts
    16
    Rep Power
    0
    Hi JonLed,

    I don't agree with you.

    I've done the following test.
    - Generate 1 million numbers between 1 and 2
    - Add it to the corresponding array element
    - Evaluate the probability

    the results:
    1: 49.882%
    2: 50.118%

    Here is the code:
    <?
    define(MAXLOOP,1000000);
    srand((double)microtime()*1000000);

    $arr[1]=0;$arr[2]=0;

    while($i++<MAXLOOP)
    $arr[rand(1,2)]++;

    echo "1: ".($arr[1]/MAXLOOP*100)."%n";
    echo "2: ".($arr[2]/MAXLOOP*100)."%n";

    ?>

    JBL
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Aug 2000
    Location
    Indiana
    Posts
    614
    Rep Power
    16
    Yes, I know. Read my message above.

    srand((double)microtime()*1000000);

    Is what I left out. (This seeds the random number).

Similar Threads

  1. random number script
    By sander1971 in forum ASP Programming
    Replies: 4
    Last Post: January 27th, 2004, 09:48 AM
  2. random number
    By jrthor2 in forum Java Help
    Replies: 2
    Last Post: January 22nd, 2004, 07:42 AM
  3. Random(): Making each number only appear once
    By NiXeN in forum C Programming
    Replies: 8
    Last Post: January 2nd, 2004, 07:53 PM
  4. Replies: 1
    Last Post: November 22nd, 2003, 03:02 PM
  5. Make a different number by random function
    By bluesky_vn in forum PHP Development
    Replies: 2
    Last Post: November 12th, 2003, 04:18 AM

IMN logo majestic logo threadwatch logo seochat tools logo