Why am I getting different results from two forms of the same math expression [javascript]?

Viewed 60

Knowing that: x^2 - 4y^2 = (x - 2y)*(x + 2y)

enter image description here

I wrote the following code:

x = 450000005;
y = 225000002;
n = x * x - 4 * y * y;
m = (x - 2 * y) * (x + 2 * y);
console.log(n, m);

And the output is:

900000032 900000009

So what happens inside JavaScript that makes these two expressions have different results? (It doesn't happen for all numbers!)

2 Answers

Your first calculation is exceeding Number.MAX_SAFE_INTEGER, which means it cannot be accurately represented. Using BigInts instead will produce the correct results.

console.log("Is 450000005 * 450000005 (x * x) safe?",
  Number.isSafeInteger(450000005 * 450000005));
x = 450000005n;
y = 225000002n;
n = x * x - 4n * y * y;
m = (x - 2n * y) * (x + 2n * y);
console.log(n.toString(), m.toString());

The numbers you're using are too high for JavaScript's implementation of IEEE 754 to be accurate at the less significant figures. Number.MAX_SAFE_INTEGER is:

console.log(Number.MAX_SAFE_INTEGER);

which x * x (among other expressions) surpasses.

Use BigInts instead:

x = 450000005n;
y = 225000002n;
n = x * x - 4n * y * y;
m = (x - 2n * y) * (x + 2n * y);
console.log(String(n), String(m));

Related