Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
137
rated 0 times [  144] [ 7]  / answers: 1 / hits: 12091  / 11 Years ago, thu, december 26, 2013, 12:00:00

Was thinking through the logic and it seemed that Math.floor(Math.random() * 255) would generate uneven probabilities of each value being generated.



For example, a number of values can round down to 254, but only when Math.random() generates exactly 1 will the output be 255. How uneven the probabilities are depends on how many decimal digits Math.random() generates to.



Am I incorrect in my thinking here or is there a more balanced way to generate a set of random integers?


More From » math

 Answers
4

Math.random() will always generate a number that is strictly less than 1 (i.e, 0 ≤ x < 1), so Math.floor(Math.random() * 255) will generate a random number between 0 and 254.



Use Math.floor(Math.random() * 256) to generate a number between 0 and 255. Yes, the results will be evenly distributed.


[#49210] Tuesday, December 24, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
isham

Total Points: 69
Total Questions: 86
Total Answers: 86

Location: Anguilla
Member since Sun, Jan 29, 2023
1 Year ago
;