-
Posts
3 -
Joined
-
Last visited
Content Type
Profiles
Forums
Events
Posts posted by Stickler999
-
-
13 hours ago, Ingolme said:
The "+1" makes it as likely as the other numbers.
If you use Math.round(), what you get is that numbers on both ends have only half the probability as the numbers in the middle, and in your example 11 would be the number at the end.
I don't agree with you. E.g. you want "0" or "1" as random numbers. According to the example at the reference page it should work like this:
console.log(Math.floor(Math.random()*1+0));
But the result is always "0". This code gives "0" or "1":
console.log(Math.round(Math.random()*1+0));
I'm not clear if
console.log(Math.floor(Math.random()*2+0));
gives a better "randomnes" for 0 oder 1? Any Mathematicians here?
-
https://www.w3schools.com/jsref/jsref_random.asp
There it says:
ÂQuoteReturn a random number between 1 and 10
Math.floor((Math.random() * 10) + 1);
Â
But with .floor() the result "10" is very unlikely, isn't it?
I would prefer .round()
Math.round(Math.random()*10+1);
Â
Examples for Math.random() maybe misleading!?
in JavaScript
Posted
So, I implemented a small testcode and found out, that we both were wrong 😉
For two integers "min" and "max" (including both) I get a good eval distribution of integer random numbers with this function:
Â
Math.floor(Math.random()*(max+1)+min);
Mozilla docs show a slightly different variant:
Â
Math.floor(Math.random() * (max - min + 1)) + min;
which seams to give the same results.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random