seedrandom icon indicating copy to clipboard operation
seedrandom copied to clipboard

arc4.g in prng function sometimes returns NaN

Open kgh-85 opened this issue 3 years ago • 6 comments

arc4.g in prng function sometimes (rare) returns NaN. Software used: Scripting interface of Adobe After Effects 2020

For folks having the same issue: I did this (ugly) quickfix which works:

  // This function returns a random double in [0, 1) that contains
  // randomness in every bit of the mantissa of the IEEE 754 value.
  var prng = function() {
    var n = arc4.g(chunks);             // Start with a numerator n < 2 ^ 48
    while (isNaN(n)) {                  //   [KGH] Quickfix
      n = arc4.g(chunks);               //   [KGH] Quickfix
    }                                   //   [KGH] Quickfix
    var d = startdenom,                 //   and denominator d = 2 ^ 48.
        x = 0;                          //   and no 'extra last byte'.
    while (n < significance) {          //   Fill up all significant digits by
      n = (n + x) * width;              //   shifting numerator and
      d *= width;                       //   denominator and generating a
      x = arc4.g(1);                    //   new least-significant-byte.
      while (isNaN(x)) {                //   [KGH] Quickfix
        x = arc4.g(1);                  //   [KGH] Quickfix
      }                                 //   [KGH] Quickfix
    }
    while (n >= overflow) {             // To avoid rounding up, before adding
      n /= 2;                           //   last byte, shift everything
      d /= 2;                           //   right using integer math until
      x >>>= 1;                         //   we have exactly the desired bits.
    }
    return (n + x) / d;                 // Form the number within [0, 1).
  };

kgh-85 avatar Nov 08 '20 22:11 kgh-85