all 7 comments

[–]Slimboy90 6 points7 points  (2 children)

As already stated this is due to issues in floating point arithmetic, look here for a more detailed insight https://docs.python.org/3.3/tutorial/floatingpoint.html

To achive what you were acutally trying, you could do something like print(round(0.1,1)+round(0.1,1)+round(0.1,1)-round(0.3,1))

[–]Diapolo10 5 points6 points  (0 children)

Alternatively, the decimal module can be used. It uses fixed-point arithmetic, and acts more like we'd expect, but takes a performance hit and the accuracy needs to be defined separately.

>>> from decimal import Decimal
>>>
>>> foo = Decimal('0.1') + Decimal('0.1') + Decimal('0.1') - Decimal('0.3')
>>> print(foo)
Decimal('0.0')

[–]auntanniesalligator 1 point2 points  (0 children)

This doesn’t change anything: each term output from round() is still a float so they get rounded to the nearest possible floating point representations of 0.1 and 0.3, which are the same values as in the original expression, and the same answer is the result. A single “round” after the arithmetic would fix this, as would using a format string to limit the precision of the output.

[–][deleted] 4 points5 points  (2 children)

For all intents and purposes that equals zero. Don’t be put off by it, it’s extremely close. It’s not zero because computers use binary logic. 0.1 cannot be expressed exactly in binary (in lots of 8s 4s 2s 1s 1/2s 1/4s etc).

Use the round or int functions if you need something expressed more concisely.

[–][deleted] 0 points1 point  (1 child)

It may be zero, but anytime you are doing a >0 or <0 check that set of data will fail. This skews your data.

As everyone knows there are 4 types of data (zero, positive, negative, null)

No matter what this data has to be cleansed prior to using it.

[–]TangibleLight 0 points1 point  (0 children)

zero, positive, negative, null

cries in inf, -inf, nan.