Question

>>> sum([0.3, 0.1, 0.2])
0.6000000000000001

>>> sum([0.3, 0.1, 0.2]) == 0.6
False

What can I do to make the result be exactly 0.6? I don't want to round the result to a certain number of decimal digits because then I could lose precision for other list instances.

Was it helpful?

Solution

A float is inherently imprecise in pretty much every language because it cannot be represented precisely in binary.

If you need exact precision use the Decimal class:

from decimal import Decimal

num1 = Decimal("0.3")
num2 = Decimal("0.2")
num3 = Decimal("0.1")

print(sum([num1, num2, num3]))

Which will return the very pleasing result of:

Decimal('0.6')  # One can do float() on this output to get plain (0.6).

Which conveniently is also a Decimal object with which you can work.

OTHER TIPS

Use math.fsome() instead of sum().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top