Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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!)

like image 741
Gudarzi Avatar asked Dec 31 '22 18:12

Gudarzi


1 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());
like image 92
Unmitigated Avatar answered Jan 14 '23 15:01

Unmitigated