• javascript 随机数


    // 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 >> 16);
              high += low;
              low += high;
              return high;
            }
          })();
    
          p(random())
    
    
  • 相关阅读:
    MVC知识点01
    MVC知识点02
    ADO.NET基础01
    WinForm,MVC知识点
    C#基础01
    28、对多次使用的RDD进行持久化或Checkpoint
    27、优化数据结构
    26、高性能序列化类库
    25、诊断内存的消耗
    24、Checkpoint原理剖析
  • 原文地址:https://www.cnblogs.com/rubylouvre/p/1846941.html
Copyright © 2020-2023  润新知