McKirahan said:
Not really.
[...]
function getRandomNum(lbound, ubound) {
var num = Math.floor(Math.random() * (ubound - lbound)) + lbound;
document.forms[0].text.value = num;
}
- Let lbound be 1.
- Let ubound be 10.
- Let Math.random() return 0.99.
- That returns
Math.floor(0.99 * (10 - 1)) + 1
= Math.floor(8.91) + 1
= 8 + 1
= 9
Since Math.random() always returns something less than 1, it is not possible
that the result is 10. But remember: we are speaking of a random integer
in the _closed_ interval [x, y], that is, the bounds are included. If the
upper bound is y and y is an integer, the probability of returning y should
be greater than zero. Meaning that your algorithm computes a random
integer in the right-hand side open interval [x, y) which is not what was
specified.
This problem can be solved by using Math.round() instead of Math.floor() and
rounding a computed floating-point number. With
function getRandomNum(lbound, ubound)
{
return Math.round(Math.random() * (ubound - lbound) + lbound);
}
document.forms[0].text.value = getRandomNum(1, 10);
- Let lbound be 1.
- Let ubound be 10.
- Let Math.random() return 0.99.
- That returns
Math.round(0.99 * (10 - 1) + 1)
= Math.round(0.99 * 9 + 1)
= Math.round(8.91 + 1)
= Math.round(9.91)
= 10
- Let lbound be 1.
- Let ubound be 10.
- Let Math.random() return 0.01.
- That returns
Math.round(0.01 * (10 - 1) + 1)
= Math.round(0.01 * 9 + 1)
= Math.round(0.09 + 1)
= Math.round(1.09)
= 1
Since Math.random() will never return something less than 0, and always
something less than 1 (ECMAScript 3, 15.8.2.14), that algorithm is safe.
PointedEars