Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Math.random() rounds down when values are close to 0 #83

Open
hellopir2 opened this issue Aug 28, 2024 · 0 comments
Open

Math.random() rounds down when values are close to 0 #83

hellopir2 opened this issue Aug 28, 2024 · 0 comments

Comments

@hellopir2
Copy link

hellopir2 commented Aug 28, 2024

I don't know if this is ever possible to reproduce with any (known) seed, but if the next 120 arc4 outputs are 0, followed by a value less than 16, d will overflow to Infinity, making all outputs regardless of value 0. This means that contrary to what the comment // randomness in every bit of the mantissa of the IEEE 754 value. says, it doesn't actually produce any values between 0 and 2^-964.

This can be fixed by changing d to the log_0.5 of the actual denominator and forcing d <= 1074. If this is going to be fixed, a better solution would be to just change the hardcoded constants and add new ones, but here is a quick fix I made.

  var prng = function() {
    var n = arc4.g(chunks),                 // Start with a numerator n < 2 ^ 48
        d = Math.log2(startdenom),          //   and denominator d = 48.
        x = 0;                              //   and no 'extra last byte'.
    while (n < significance && d < 1074) {  // Fill up all significant digits by
      n = (n + x) * width;                  //   shifting numerator and
      d += Math.log2(width);                //   denominator and generating a
      x = arc4.g(1);                        //   new least-significant-byte.
    }
    while (n >= overflow || d > 1074) {     // To avoid rounding up, before adding
      n /= 2;                               //   last byte, shift everything
      d -= 1;                               //   right using integer math until
      x >>>= 1;                             //   we have exactly the desired bits.
    }
    return (n + x) * Math.pow(2, -d);       // Form the number within [0, 1).
  };

This is not an issue anyone will ever encounter, but I just noticed this and wanted to comment on it :).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant