Hello code newbies:
I have a fun JavaScript question for you.
Is the following expression True
or False
?
Math.pow(2, 53) == Math.pow(2, 53) + 1
Before answering, please test your answer in your favorite JavaScript environment.
Explain!
Hello code newbies:
I have a fun JavaScript question for you.
Is the following expression True
or False
?
Math.pow(2, 53) == Math.pow(2, 53) + 1
Before answering, please test your answer in your favorite JavaScript environment.
Explain!
For further actions, you may consider blocking this person and/or reporting abuse
InterSystems Developer -
Random -
Rahul Raveendran -
Rahul Raveendran -
Top comments (6)
At first, I was confused why this would not return
false
, but of course you wouldn't have posted this if it would returnfalse
. πWhile looking into why these statements are evaluated to be equal, I stumbled upon an even more interesting problem: When you try to enter exceedingly big numbers into a JavaScript console, they will be returned similiarly but not with the exact same value. For example,
9007199254740992111
will be transformed into9007199254740992000
. This sounded awfully like floating point issues. After having a look, the way integers are stored in JavaScript engines using 64 bits, which means there's a limit to correctly display numbers above a certain threshold. And that threshold appears to be 2^53, which explains why you took those parameters forMath.pow
!Previously, I was only aware of examples where floating point issues arise with the storage of numbers smaller than zero, leading me to think it would be a "comma problem" (for example
0.1 + 0.2 != 0.3
), but this example made clear for me that this of course can also happen for big numbers.This thread helped me understand the details, it's worth checking out.
Actually,
Math.pow(2, 53) === Math.pow(2, 53) + 1
(triple equals), unless your wrap in BigInt.Every programming languages have a concept of
Number.MAX_SAFE_INTEGER
.The MAX_SAFE_INTEGER in Javascript is 2^53 - 1, meaning that in this range integers are safe to be represented and compared. Any integer above this value will not be safe to be compared anymore, thus 2^53 == 2^53 + 1 evaluates to true, which is mathematically incorrect.
Others have answered with scientific explanation. Mine will be much more easier to understand. Much more graphical I would say.
Its true because the console says so :)
Welp, I actually expected JS to behave same way as python and produce
false
. I've never been so wrong.Yeah, Python doesn't tell you about
short
,long
,float
anddouble
and it automates this; but for JavaScript, it is alwaysdouble
.I am actually stumbled in standard Python that it is
False
, instead of throwing an error. It will not be the case in Kotlin.Now, I can ask on StackOverflow, but SO is such as scary place. There is this in Quora, but not many wants to answer.
It seems that it is bignum, actually. You don't even have to care about Decimal, unless you care about
0.1 + 0.2