2 Replies Latest reply on Aug 5, 2006 7:47 AM by lumpthing

# Trouble with random numbers

I want to create a variable, xSpeed, which has an equal chance of being either 10, -10 or 0. Here's what I've got so far:

xRandom = random(3);
if (xRandom<=1) {
xSpeed = 10;
} else if (xRandom<=2) {
xSpeed = -10;
} else {
xSpeed = 0;
}

So there should be an equal chance of xSpeed being implemented as 10, -10 or 0 right? Instead I am finding that it is always either 10 or -10.

If I change xRandom = random(3); to xRandom = random(4); then each value has an equal chance of being implemented. But that should be the case for random(3) surely!???

Also, if I change xRandom = random(3); to xRandom = Math.random(3); then xSpeed always seems to end up as 10. What's with that??? What difference does adding Math. make???

I must be missing something important about how random() works because this isn't making any sense to me :(.
• ###### 1. Trouble with random numbers
random(Number) picks a pseudorandom number from zero, to 1 minus the number you entered.
This makes it particularly useful with arrays, because they are indexed starting with zero.

Try the following:

var numberArray = [10,-10,0];
xSpeed = numberArray[random(3)];
• ###### 2. Re: Trouble with random numbers
Perfect. Thanks very much