Skip navigation
Currently Being Moderated

Math.random repeating in loops

Jul 29, 2012 6:31 PM

I'm having a persistent issue with Math.random returning the same value multiple times if called in quick succession, such as when used in a loop. For example,

 

for (var i:int = 0; i < 10; i++) {

     trace(Math.ceil(Math.rand() * 20));

}

 

might output a set of numbers like 4,4,3,6,6,6,6,17,17,17.

 

I'm guessing that the system clock is involved in the random calculation and calling the Math.random function too quickly will return the same value because the clock hasn't changed yet, but that's just a guess. Anyway, this behavior of course wreaks havoc with balance in games and I'm wondering if there is a way to get around it that I'm not aware of. Thanks for any ideas.

 
Replies
  • Currently Being Moderated
    Jul 29, 2012 7:11 PM   in reply to xTLS

    I do not observe anything of the sort if I correct the code you show and run it.  The smaller the limit of the possible outcomes, the more likely the same values will appear, but with a spread of 20 possible values I do not see the amount of repetition you showed over several runs.

     
    |
    Mark as:

More Like This

  • Retrieving data ...

Bookmarked By (0)

Answers + Points = Status

  • 10 points awarded for Correct Answers
  • 5 points awarded for Helpful Answers
  • 10,000+ points
  • 1,001-10,000 points
  • 501-1,000 points
  • 5-500 points