• Global community
    • Language:
      • Deutsch
      • English
      • Español
      • Français
      • Português
  • 日本語コミュニティ
    Dedicated community for Japanese speakers
  • 한국 커뮤니티
    Dedicated community for Korean speakers
Exit
0

Math.random repeating in loops

Contributor ,
Jul 29, 2012 Jul 29, 2012

Copy link to clipboard

Copied

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.

TOPICS
ActionScript

Views

783

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
LEGEND ,
Jul 29, 2012 Jul 29, 2012

Copy link to clipboard

Copied

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.

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Contributor ,
Jul 29, 2012 Jul 29, 2012

Copy link to clipboard

Copied

LATEST

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

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines