user4027720
user4027720

Reputation:

Random Number Generation in Javascript going outside of range

My random number generation for my JavaScript program sometimes goes out of bounds from the range that I set.

My code looks like:

rand1 = Math.floor(Math.random()*max)+min;

where my max is the upper bound for my number and the min is the lower bound. When my min is 1 the code seems to work fine, but if I start at say 10 and have my upper bound at 55 it messes up. In that particular example I sometimes get 57 and so on.

Upvotes: 0

Views: 1085

Answers (4)

gzp___
gzp___

Reputation: 388

Hi you are getting a wrong result because the formula is wrong. Try to use

function getRandomArbitrary(min, max) {
  return Math.floow(Math.random() * (max - min) + min);
}

Documentation source

Upvotes: -1

Pabs123
Pabs123

Reputation: 3435

To add on to the other answers, this will give you an inclusive range:

Math.floor(Math.random() * (max - min + 1)) + min;

Upvotes: 0

Snowmonkey
Snowmonkey

Reputation: 3761

That is all relevant code. Problem is, you do the math random thing, then you shift the whole thing beyond the max. Try this:

function getRandomArbitrary(min, max) {
  return Math.random() * (max - min) + min;
}

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386756

You need to take the delta from max and min.

rand1 = Math.floor(Math.random() * (max - min)) + min;

Upvotes: 1

Related Questions