0

OK something weird happened to me I did the following equality comparison in Nodejs and surprisingly it replied with true.

(2 ** 64) - 1000 === (2 ** 64) // true

Why is that?

> for (let i = 0; i<=20; i++)
... console.log(i, (2 ** 64) - (2 ** i) === (2 ** 64))
0 true
1 true
2 true
3 true
4 true
5 true
6 true
7 true
8 true
9 true
10 true
11 false
12 false
13 false
14 false
15 false
16 false
17 false
18 false
19 false
20 false
pouya
  • 3,400
  • 6
  • 38
  • 53
  • In addition to the duplicate link, we sort of would expect this, since `2^64` is a very large number, and floating point arithmetic is not exact anyway. – Tim Biegeleisen Jun 10 '19 at 08:30
  • This is the biggest number you can accurately represent: 9007199254740992. 2 ** 53 – TKoL Jun 10 '19 at 08:31
  • Try in your console 2 ** 53, 2 ** 53 + 1, 2 ** 53 - 1 – TKoL Jun 10 '19 at 08:31
  • If you want to do math on bigger numbers, you'll have to use a library specifically for big numbers – TKoL Jun 10 '19 at 08:32
  • thanks @TKoL so nodejs computes 2 ** (bigger than 53) but can't do a comparison on it? – pouya Jun 10 '19 at 08:48
  • 1
    In this case it looks like its computing it correctly, but I wouldn't even rely on it to compute the correct value for bigger values than 53 in general. And yes, any additional computations on the same value are very unlikely to come out correct. – TKoL Jun 10 '19 at 09:03

0 Answers0