DEV Community

Jesse Warden
Jesse Warden

Posted on • Originally published at jessewarden.com

Seeing JavaScript Math.random Not Be So Random

Read Flow Metrics. Learned about Monte Carlo Simulations. Learned you can use that to make accurate estimations with lots of data points. It’s one thing to hear “Math.random in JavaScript isn’t random”, and another to see it after only 1,000 samples. SOO COOL!

Context: “If you run Math.random enough between 1 & 6, you’re most likely to get 3.5”.

Code: https://ellie-app.com/kVjPdGBbP2ka1

Uses Elm Charts (horribly, sorry, I didn’t spend time styling it)

Article which helped get me some code: https://questsincode.com/posts/monte-carlo-simulation-javascript

Top comments (6)

Collapse
 
mellen profile image
Matt Ellen-Tsivintzeli

If you want to see the distribution of dice rolls, I think this codepen does an OK job:

Collapse
 
jesterxl profile image
Jesse Warden

Rad, thank you! The blog post I linked to has one embedded too, but I like how this one uses Map.

Collapse
 
mellen profile image
Matt Ellen-Tsivintzeli • Edited

Thanks, Jesse.

I hope that the frequencies my JS generates can demonstrate that the distribution of random numbers between 1 and 6 is fairly even, rather than being biased. Although the PRNG in use cannot be truly random, it does a good enough job.

I think this is basically what your Monte Carlo simulation tells you, too. It's not saying you'll get 3.5, it's saying the average is 3.5.

Collapse
 
redbar0n profile image
Magne • Edited

Not sure why Math.random eventually settling around the theoretical mean would mean it is not random? Wouldn't it settle around the theoretical mean even if it were random? As per The Law of Large Numbers. Ref: math.stackexchange.com/questions/4...

I'm sure Math.random is not actually fully random, as any algorithm without a bit of outside entropy would be deterministic, but I'm just curious about the inference made in this post.

The Y axis starts at 1 on your graph, not 0. So there are only 5 intervals, and 2.5 interval on each side of the mean. Seeing the mean settle half-way is expected, no?

Collapse
 
jesterxl profile image
Jesse Warden

:: shrugs :: Thanks for the bug find, will attempt to fix in round 2.

Collapse
 
naucode profile image
Al - Naucode

Great article, you got my follow, keep writing!