2 Replies Latest reply: Jul 29, 2012 8:53 PM by xTLS RSS

    Math.random repeating in loops

    xTLS Community Member

      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.

        • 1. Re: Math.random repeating in loops
          Ned Murphy CommunityMVP

          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.

          • 2. Re: Math.random repeating in loops
            xTLS Community Member

            I should have been more clear that was a vastly oversimplified example. That code specifically (after you change rand to random, whoops) won't usually produce the same value in a row more than twice. But then I've got code (all too long to post of course) with function calls, loops, etc, generating the same number six or more times in a row in some cases.

             

            edit: Well, in this case it was a convoluted and stupid bug, actually unrelated to the random number generation. So my bad >_< . I've had similar problems several times in the past, though they were in areas less obvious to the end user; I don't remember if or how I resolved them, so for all I know they were similarly deceptive bugs