Math.random和JavaScript中的Web编程 [英] Math.random and web programming in JavaScript

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

问题描述

根据此Stack Overflow线程,Math.random()在JavaScript取决于浏览器或操作系统。基本上,它意味着JavaScript没有用于生成均匀随机变量的标准算法。 此主题似乎暗示Chrome的统一随机数算法特别糟糕。

According to this Stack Overflow thread, Math.random() in JavaScript depends on the browser or the operating system. Basically, it implies that JavaScript does not have a standard algorithm for generating uniform random variables. This thread seems to suggest that Chrome's uniform random number algorithm is particularly bad.

在我的程序中,我尝试根据一些信息和随机噪声来理解用户的行为。我对Math.random()生成的数字使用Box-Muller变换来生成高斯随机数。这是否意味着使用一个浏览器的用户将遇到不同类型的噪音?注意我使用Box Muller因为我不关心速度,但我知道它对伪随机数的生成方式特别敏感。似乎有很多线程关于为什么Math.random()是坏的,但在线程中并没有太多关于实际使用的内容。什么是最佳做法?有什么东西我应该特别注意,因为我使用Box-Muller转换为高斯数字?

In my program I try to understand how the user behaves based on some information plus random noise. I use a Box-Muller transform on numbers generated by Math.random() to generate Gaussian random numbers. Does this mean that users using one browser will be experiencing different types of noise than others? Note I use Box Muller because I don't care about speed, but I know it can be particularly sensitive to how the pseudo random numbers are generated. There seems to be lots of threads about why Math.random() is bad, but not so much within the thread on what to actually use instead. What is the best practice? Is there something that I should particularly look out for because I am using Box-Muller to convert to Gaussian numbers?

推荐答案

有一个基于xor-shift的RNG, http://en.wikipedia.org/wiki/Xorshift 应该很容易移植到JavaScript的随机性属性:

There's an xor-shift based RNG at http://en.wikipedia.org/wiki/Xorshift with good randomness properties that should port fairly readily to JavaScript:

编辑完成:

(function () {
    var x = 123456789;
    var y = 362436069;
    var z = 521288629;
    var w = 88675123;
    var f = Math.pow(2, -32);

    Object.defineProperty(Math, 'xor128', {
        value: function () {
            var t = x ^ (x << 11);
            x = y;
            y = z;
            z = w;
            w = w ^ (w >>> 19) ^ (t ^ (t >>> 8));

            return (w >>> 0) * f;  // convert to floating point          
        }
    });

})();

注意:这只使用生成的128位中的32位来产生浮点结果。从理论上讲,你可以将另一个状态变量中的另外20位组合起来产生52位结果。

NB: this only uses 32 bits of the 128 generated to produce the floating point result. In theory you could combine another 20 bits from one of the other state variables to produce 52 bits of result.

我能看到的最重要的问题是它没有不支持播种 - 它总是生成相同的序列。

The most significant issue with it I can see is that it doesn't support seeding - it'll always generate the same sequence.

这篇关于Math.random和JavaScript中的Web编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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