1

Will I possibly loose any decimal digits (precision) when multiplying Number.MAX_SAFE_INTEGER by Math.random() in JavaScript?

I presume I won't but it'd be nice to have a credible explanation as to why 😎

Edited, In layman terms, we're dealing with two IEEE 754 double-precision floating-point numbers, one is the maximal integer (for double-precision), the other one is fractional with quite a few digits after a decimal point. What if (say) I first converted them to quadruple-precision format, then multiplied, and then converted the product back to double-precision, would the result be any different?

const max = Number.MAX_SAFE_INTEGER;
const random = Math.random();
console.log(`\
MAX_SAFE_INTEGER: ${max}, \
random: ${random}, \
product: ${max * random}`);

For more elaborate examples, I use it to generate BigInt random numbers.

3 Answers 3

1

Your implementation should be safe - in theory, all numbers between 0 and MAX_SAFE_INTEGER should have a possibility of appearing, if the engine implementing Math.random uses a completely unbiased algorithm.

But an absolutely unbiased algorithm is not guaranteed by the specification - the numbers chosen are meant to be psuedo random, not truly, completely random. (does such a thing even exist? it's debatable...) Modern versions V8 and some other implementations use an algorithm with a period on the order of 2 ** 128, larger than MAX_SAFE_INTEGER (2 ** 53 - 1) - but it'd be completely plausible for other implementations (especially older ones) to have a much smaller period, resulting in certain integers within the range being picked much more often than others.

If this is important for your script (which is pretty unlikely in most situations, I'd think), you might consider using a higher-quality random generatior than Math.random - but it's almost certainly not worth worrying about.

2
  • I'd be ok with reappearing numbers, but, in simple words, I was rather concerned that I multiple one big IEEE-754-represented integer number by another very small fractional one. So as a result, I thought I might be loosing some precision. Are you saying this is not the case? I admit I need to read up on IEEE-754 format, it's been a while since my Uni days :)
    – noseratio
    Commented Jun 15, 2021 at 2:58
  • 1
    All numbers will have 52 bits of precision, whether huge or small, decimal or not, and that precision will carry over when the numbers are operated on (and then less significant digits are discarded), so you should be fine. Commented Jun 15, 2021 at 3:01
1

What if (say) I first converted them to quadruple-precision format, then multiplied, and then converted the product back to double-precision, would the result be any different?

It could be in cases where the rounding behaves differently between multiplying two doubles vs converting quadruple to double, but the main problem remains the same. The spacing between representable doubles in the range from 2n to 2n+1 is 2n−52. So between 252 and 253 only whole numbers can be represented, between 251 and 252 only every 0.5 can be represented, etc.

If you want more precision you could try decimal.js. The library is included on that documentation page so you can try these out in your console.

Number.MAX_SAFE_INTEGER*.9
8106479329266892
new Decimal(Number.MAX_SAFE_INTEGER).mul(new Decimal(0.9)).toString()
"8106479329266891.9"
1
  • Thanks and hey, nice to hear from you @rjschnorenberg! And of course, you're right :) I've verified that with C#, where double is represented by the same binary64 format: dotnetfiddle.net/m6HKuL
    – noseratio
    Commented Jun 15, 2021 at 7:37
0

Both answers are correct, but I couldn't help running this little experiment in C#, where double is the same thing as Number in JavaScript (fiddle):

using System;

public class Program
{
  public static void Main()
  {
    const double MAX_SAFE_INT = 9007199254740991;
    Decimal maxD = Convert.ToDecimal(MAX_SAFE_INT.ToString());
    var rng = new Random(Environment.TickCount);
    for (var i = 0; i < 1000; i++) 
    { 
        double random = rng.NextDouble();
        double product = MAX_SAFE_INT * random;
      
        // converting via string to workaround the "15 significant digits" limitation for Decimal(Double)
        Decimal randomD = Decimal.Parse(String.Format("{0:F18}", random));
        
        Decimal productD = maxD * randomD;
        double converted = Convert.ToDouble(productD);
        if (Math.Floor(converted) != Math.Floor(product)) 
        {
          Console.WriteLine($"{maxD}, {randomD, 22}, products: decimal {productD, 32}, converted {converted, 20}, original {product, 20}");
        }
    }
  }
}

As far as I'm concerned, I'm still getting the desired distribution of the random numbers within the 0 - 9007199254740991 range.

Here is a JavaScript playground code to check for possible recurrences.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.