Does JavaScript's Math.random() Method Create Uniform Random Variables?

JavaScript has a built-in Math.random() method for creating random variables. I've built a simulator to test whether this method creates uniform random variables. The JavaScript 's Math.random() method originally creates a random number from 0-1 with 1 excluded. In order to visualize the results, I multiply 100 random numbers created by the Math.random() method by 10 and round them down.

Change the Range of Random Variables Created By Math.random()

The JavaSript Math.random() method creats continuous uniform random variable ranged from 0 to 1 with 1 excluded. If we can expand its range buy multiplying the Math.random() method with a scale parameter. For example, we can use Math.ranomd()*10 to generate continuous uniform random variable ranged from 0 to 10 with 10 excluded. We can also move the lower and upper bounds by adding a parameter to the Math.random() method. For exampe, 10 + Math.random()*10 creates continuous uniform random variable ranged from 10 to 10 with 10 excluded.
The general formula is this: a + Math.random()*b, where a is the lower bound, b is the range.
Formula Range
10*Math.random() 0-10(excluded)
20*Math.random() 0-20(excluded)
10 + 10*Math.random() 10-20(excluded)
20 + 10*Math.random() 20-30(excluded)

Get Formula for Creating Continuous Uniform Random Variable in JavaScript

Lower Bound:
Range:
Random Numbers:
<script>
  	10 + 10 * Math.random();
</script>

How to Create Discete Uniform Random Variables in JavaScript

Since the native JavaScript Math.ranomd() method creates continuous random variables, we can apply a toFixed() method to the random variables to make them discrete. For example, if we want to create discrete uniform random variable ranged from 0 to 9, we can use (10*Math.random()).toFixed(0);
<button onclick = "showDiscrete.innerHTML += (10*Math.random()).toFixed(0)">Get Random Number</button>
<div id = "showDiscrete"></div>
If we throw in different integers into the toFixed() parameter, we can create discrete random variables with a defined precision.
Lower Bound:
Range:
Precisition:
Random Numbers:
<script>
  	(10 + 10 * Math.random()).toFixed(2);
</script>

Comments

Popular posts from this blog

How to Make A Reusable Image Slideshow HTML Component With Vanilla JavaScript

HTML Tags and Inline CSS that Work In Plotly.js Title

How to Type Spaces In HTML Input And Display In the Browser