JavaScript的Math.random是多么随机? [英] How random is JavaScript's Math.random?

查看:459
本文介绍了JavaScript的Math.random是多么随机?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

6年来,我的网站上有一个随机数生成器页面。很长一段时间,它是Google上随机数生成器的第一个或第二个结果,并且已被用于在论坛和博客上决定数十个(如果不是数百个)竞赛和绘图(我知道因为我看到了我的推荐人)网络日志,通常去看看。

For 6 years I've had a random number generator page on my website. For a long time, it was the first or second result on Google for "random number generator" and has been used to decide dozens, if not hundreds of contests and drawings on discussion forums and blogs (I know because I see the referrers in my web logs and usually go take a look).

今天,有人通过电子邮件告诉我它可能不像我想的那么随意。她尝试生成非常大的随机数(例如,介于1和10000000000000000000之间),发现它们几乎总是相同的位数。实际上,我将函数包装在一个循环中,因此我可以生成数千个数字,当然,对于非常大的数字,变化只有大约2个数量级。

Today, someone emailed me to tell me it may not be as random as I thought. She tried generating very large random numbers (e.g., between 1 and 10000000000000000000) and found that they were almost always the same number of digits. Indeed, I wrapped the function in a loop so I could generate thousands of numbers and sure enough, for very large numbers, the variation was only about 2 orders of magnitude.

为什么?

这是循环版本,所以你可以自己试试:

Here is the looping version, so you can try it out for yourself:

http://andrew.hedges.name/experiments/random/randomness.html

它包括从 Mozilla开发者网络和1997年的一些代码,我刷掉了一个不再存在的网页(Paul Houle的Central Randomizer 1.3)。查看来源以了解每种方法的工作原理。

It includes both a straightforward implementation taken from the Mozilla Developer Network and some code from 1997 that I swiped off a web page that no longer exists (Paul Houle's "Central Randomizer 1.3"). View source to see how each method works.

我已阅读此处其他地方关于 Mersenne Twister。我感兴趣的是为什么JavaScript的内置 Math.random 函数的结果没有更大的变化。谢谢!

I've read here and elsewhere about Mersenne Twister. What I'm interested in is why there wouldn't be greater variation in the results from JavaScript's built-in Math.random function. Thanks!

推荐答案

给出1到100之间的数字。

Given numbers between 1 and 100.


  • 9有1位数(1-9)

  • 90有2位数(10-99)

  • 1有3位数(100)

给定1到1000之间的数字。

Given numbers between 1 and 1000.


  • 9有1位数

  • 90有2位数

  • 900有3位数

  • 1有4位数

  • 9 have 1 digit
  • 90 have 2 digits
  • 900 have 3 digits
  • 1 has 4 digits

依此类推。

所以如果你选择一些随机,然后绝大多数选定的数字将具有相同的位数,因为绝大多数可能的值具有相同的位数。

So if you select some at random, then that vast majority of selected numbers will have the same number of digits, because the vast majority of possible values have the same number of digits.

这篇关于JavaScript的Math.random是多么随机?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆