A Flash Developer Resource Site

Results 1 to 4 of 4

Thread: a more "random" random....

  1. #1
    Member
    Join Date
    Jul 2005
    Posts
    63

    a more "random" random....

    I'm currently working on a game where I'd like a variable to return one of three values randomly.

    Here is the code that I'm using for my variable....

    Code:
    compNumber = Math.round (Math.random ()*2);
    Right now, I'm getting the numbers "0" and "1" almost 90% percent of the time, with a "2" value rarely, which would make my game very quick to figure out and defeat. I'd like to get something closer to true random value, but haven't been able to figure out how to change that line in order to achieve that.

    Can anyone tell me where I'm going wrong?

  2. #2
    Will moderate for beer
    Join Date
    Apr 2007
    Location
    Austin, TX
    Posts
    6,801
    round is not the function to use. Look at what random has to return for each possibility:
    0 - 0.25 = 0
    0.25 - 0.75 = 1
    0.75 - 1 = 2

    So your distribution is not even close to uniform. Use floor instead of round and 3 instead of 2, and you'll get a uniform distribution (assuming random produces a uniform distribution)
    0 - 0.3333... = 0
    0.3333... - 0.6666... = 1
    0.666... - 1 = 2
    Code:
    compNumber = Math.floor(Math.random() * 3);

  3. #3
    :
    Join Date
    Dec 2002
    Posts
    3,518
    ...
    Last edited by dawsonk; 08-02-2010 at 10:12 AM. Reason: too slow

  4. #4
    Member
    Join Date
    Jul 2005
    Posts
    63
    That seems a lot better. Thanks!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  




Click Here to Expand Forum to Full Width

HTML5 Development Center