Consult W3school, and the answer is: Math.random () returns a random number from 0 to 1, which is (0,1).
Review the MDN (Mozilla Developer Network), and the explanation is: Math.random () returns a random number greater than or equal to 0, less than 1, or [0,1].
And in fact? Let's do an experiment: Cycle through Math.random () to generate 1 million random numbers, counting the number of 0 occurrences.
var m = 0, = 1000000; for (var i = 0; i < n; i++) { math.random ()===0 m++: "";}; Console.info ("The number of occurrences of the 0 is:" +m+ "Times");
The output is:
0 occurrences are: 0 times
0 times, is the number of cycles too little? Then change the number of cycles to 100 million times.
The output is:
0 occurrences are: 0 times
The result is still 0 times! Many trials were 0 times, and 0 never appeared. From this point of view, W3school's explanation seems to be more realistic.
Math.random () also has an interesting phenomenon:
We know that you can use Math.random () to return a random number between two integers (including the two integers themselves), such as returning a random integer between 1~10, in theory 1-10 the probability that each number appears is 10%, But in fact I found that the probability of 1 and 10 appearing is about half the probability of other numbers appearing! So it's not fair to use Math.random () to generate random numbers of lottery programs.
for (var i = 0; i < i++) { ~function() { var x = i+1, = 0, = 1000000; for (var j = 0; J < N; j + +) { Math.Round (Math.random ())*9+1) ===x m++: ""; }; console.info (x+ "occurrences are:" +m+ "times", "Probability:" +m/n*100+ "%"); } (i)};
Output:
1 The number of occurrences is: 55,587 probabilities: 5.5587%
2 The number of occurrences is: 111,062 probabilities: 11.1062%
3 The number of occurrences is: 110,879 probabilities: 11.08790
4 The number of occurrences is: 111,146 probabilities: 11.1146%
5 The number of occurrences is: 110,554 probabilities: 11.0554%
6 The number of occurrences is: 111,610 probabilities: 11.161%
7 The number of occurrences is: 111,345 probabilities: 11.1345%
8 The number of occurrences is: 110,724 probabilities: 11.0724%
9 The number of occurrences is: 110,450 probabilities: 11.045%
10 The number of occurrences is: 55,560 probabilities: 5.556%
by Wang Meijian from http://www.cnblogs.com/wangmeijian/p/4235907.html
Reprint please retain the attribution and source
Can the value of Math.random () be 0 or 1?