0

Note: This question has code snippets in python, but applies to most languages which throw an error or return false when dividing by 0.

I encountered this code yesterday:

print(1/(0.9-0.3-0.3-0.3))

Which gives the strange output:

9007199254740992.0

Why does this not throw a ZeroDivisionError, and why does it return that specific number?

Nico A
  • 227
  • 1
  • 14
  • 1
    Because 0.3 is not represented the way you think it is. – Maroun Aug 16 '15 at 17:43
  • 1
    How is it represented? – Nico A Aug 16 '15 at 17:44
  • 1
    related: http://stackoverflow.com/questions/21895756/why-are-floating-point-numbers-inaccurate – adelphus Aug 16 '15 at 17:45
  • Binary floating-point numbers cannot represent the numbers 0.3 and 0.9 exactly. As a result of roundoff, the expression `0.9-0.3-0.3-0.3` gets evaluated to a tiny number (of the order of the machine epsilon, i.e. about 1e-16 for double precision). If you divide 1 by a tiny number, you get a large one. See http://stackoverflow.com/questions/27786864/why-am-i-getting-incorrect-results-for-these-simple-operations-in-julia/27786912#27786912 for an explanation and a similar example. – jub0bs Aug 16 '15 at 17:45
  • I get now how they are represented but even if .3 is 0.30000000001 why would it get the strange result "9007199254740992.0 " what is special about that number? – Nico A Aug 16 '15 at 17:47
  • 1
    @TreFox There is nothing special about `9007199254740992.0`. It just happens to be the decimal representation of the result of computing the reciprocal of `0.9-0.3-0.3-0.3`. Note that it is of the order of 1e16, though. That is the only remarkable (though unsurprising) fact about this number. – jub0bs Aug 16 '15 at 17:51

0 Answers0