Write a truly inclusive random method for javascript

前端 未结 9 1476
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 11:25

Javascript\'s MATH object has a random method that returns from the set [0,1) 0 inclusive, 1 exclusive. Is there a way to return a truly random method that includes 1.

9条回答
  •  情深已故
    2020-11-30 11:52

    From what I can see from the JavaScript console in Chrome, Math.random() generates a number from 0 up to 0.9999999999999999. Taking this into account, you can get what you want by adding a modifier. For example, here's a function that will give you quasi-random float between 0 and 1, with 1 being inclusive:

    function randFloat() {
      // Assume random() returns 0 up to 0.9999999999999999
      return Math.random()*(1+2.5e-16);
    }
    

    You can try this in the console by enter 0.9999999999999999*(1+2.5e-16) -- it will return exactly 1. You can take this further and return a float between 0 and 1024 (inclusive) with this function:

    function randFloat(nMax) {
      // Assume random() returns 0 up to 0.9999999999999999
      // nMax should be a float in the range 1-1024
      var nMod;
      if (nMax<4) nMod = 2.5e-16;
      else if (nMax<16) nMod = 1e-15;
      else if (nMax<32) nMod = 3.5e-15;
      else if (nMax<128) nMod = 1e-14;
      else if (nMax<512) nMod = 3.5e-14;
      else if (nMax<1024) nMod = 1e-13;
      return Math.random()*(nMax+nMod);
    }
    

    There's probably a more efficient algorithm to be had somewhere.

提交回复
热议问题