Write a truly inclusive random method for javascript

前端 未结 9 1484
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 11:25

Javascript\'s MATH object has a random method that returns from the set [0,1) 0 inclusive, 1 exclusive. Is there a way to return a truly random method that includes 1.

9条回答
  •  半阙折子戏
    2020-11-30 11:55

    The solution I found was to use trigonometric equations.

    Because sine oscillates from Math.sin(0) = 0 and Math.sin(90) = 1. This repeats until 360 degrees which is equal to 0. However, 360 is still not highly precise so use radians which is 2 * Math.PI. You only need to take the absolute value to get rid of the negative values.

    So,

    double angle = 2 * Math.PI * Math.random() 
    double inclusive = Math.abs(Math.sin(angle)) // Math.cos(angle) also works.
    

提交回复
热议问题