Reputation:
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
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
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
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
Reputation: 386756
You need to take the delta from max
and min
.
rand1 = Math.floor(Math.random() * (max - min)) + min;
Upvotes: 1