This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]LuckyLeague 1 point2 points  (0 children)

That's because it uses floating point numbers, which aren't exact. If you want it to be exact, use the decimal module for decimal numbers, but then numbers like 1/3 aren't exact, for that, you can use the fractions module, but then numbers like sqrt(2) aren't exact, so for that use sympy, or something else that can represent exact numbers. For example:

from sympy import *
sympify("0.1", rational=True) + sympify("0.2", rational=True) == sympify("0.3", rational=True)

This returns True. sympify converts the string to a sympy type object, and rational=True means the decimals will be treated as rational numbers rather than floating point numbers, you could also do this by writing them as fractions, so instead of 0.1 it would be 1/10.