为什么Google Chrome的Math.random编号生成器不是*随机的? [英] Why is Google Chrome's Math.random number generator not *that* random?

查看:112
本文介绍了为什么Google Chrome的Math.random编号生成器不是*随机的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天当我在各种浏览器中运行一些单元测试时,我遇到了一个奇怪的bug。今天之前我曾多次在Firefox中运行测试,甚至是IE,但显然不是Chrome(v19-dev)。当我在Chrome中运行它时,它始终不能通过一项测试,因为我计算的两个值不匹配。



当我真正了解发生的情况时,我意识到问题是我假定如果我填充了一个数组,它们都是唯一的(不会有任何冲突),它们的数值是100,000 Math.random()。在Chrome浏览器中,我发现至少有两个对匹配的值超过了100,000。 Firefox和IE9从未遇到过碰撞。这里是我写的一个jsfiddle,用于测试这个数组,在数组中创建1M Math.random()条目: http://jsfiddle.net/pseudosavant/bcduj/ b / b
$ b

有谁知道为什么Chrome伪随机用于 Math.random 的数字生成器真的不是那个随机的?看起来这可能会影响任何使用 Math.random 的客户端js加密例程。

解决方案

显然,V8中的Math.random()只适用于32位值(甚至没有正确的随机化所有这些)。而32位,碰撞概率在2 ^ 16 = 65k值附近达到50%......

I ran into an odd "bug" today when I was running some unit tests in various browsers. I had run the tests in Firefox many times before today, and even IE but apparently not Chrome (v19-dev) yet. When I ran them in Chrome it consistently failed one test because two values I was calculating did not match.

When I really dug into what was happening I realized that the issue was that I was assuming that if I filled an array with 100,000 Math.random() values that they would all be unique (there wouldn't be any collisions). Turned out that in Chrome that is not true.

In Chrome I was consistently getting at least two pairs of values that matched out of 100,000. Firefox and IE9 never experience a collision. Here is a jsfiddle I wrote just for testing this that creates 1M Math.random() entries in an array: http://jsfiddle.net/pseudosavant/bcduj/

Does anyone know why the Chrome pseudo-random number generator that is used for Math.random is really not that random? It seems like this could have implications for any client-side js encryption routines that ever use Math.random.

解决方案

Apparently Math.random() in V8 only works with 32 bit values (and didn't even correctly randomize all of those in the past). And with 32 bits, the probability of a collision reaches 50% around 2^16 = 65k values...

这篇关于为什么Google Chrome的Math.random编号生成器不是*随机的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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