现在的位置: 首页 > 综合 > 正文

javascript 随机数

2012年01月10日 ⁄ 综合 ⁄ 共 1117字 ⁄ 字号 评论关闭
// by 司徒正美 http://www.cnblogs.com/rubylouvre/
      var native_random = Math.random;
      Math.random = function(min, max, exact) {
        if (arguments.length === 0) {
          return native_random();
        } else if (arguments.length === 1) {
          max = min;
          min = 0;
        }
        var range = min + (native_random()*(max - min));
        return exact === void(0) ? Math.round(range) : range.toFixed(exact);
      };

      p(Math.random())
      p(Math.random(10))
      p(Math.random(3,10))
      p(Math.random(2,10,4))

群里的人很无聊,于是提了一个问题,如何不使用Math.random实现随机数,其实当时我也不知道。下面的函数改自一个C实现:

// The idea of random mehtod is taken from
// http://ianbullard.squarespace.com/journal/2009/4/28/why-you-should-never-use-rand.html
      var random = (function(){
        var high = 1, low = 1 ^ 0x49616E42;
        var shuffle = function(seed){
          high = seed;
          low = seed ^ 0x49616E42;
        }
        return function(){
          var a = new Date()-0
          shuffle(a);
          high = (high > 16);
          high += low;
          low += high;
          return high;
        }
      })();

      p(random())

抱歉!评论已关闭.