Reputation: 33
I have an issue with floating-point numbers:
a = 0.4812
b = 0.4813
a-b
-9.999999999998899e-05
a = Decimal(0.4812)
b = Decimal(0.4813)
a-b
Decimal('-0.000099999999999988986587595718447118997573852539062500')
How can I get exactly -0.0001?
Upvotes: 3
Views: 87
Reputation: 631
If you want round it you can use this: round(-0.000099999999999988986587595718447118997573852539062500, 4)
Upvotes: -1
Reputation: 47790
You need to pass the numbers in as strings to the Decimal
constructor, if you use float literals they've already lost precision before the Decimal
object gets constructed.
>>> a = Decimal('0.4812')
>>> b = Decimal('0.4813')
>>> a - b
Decimal('-0.0001')
To illustrate more clearly:
>>> Decimal('0.4812')
Decimal('0.4812')
>>> Decimal(0.4812)
Decimal('0.481200000000000016608936448392341844737529754638671875')
Upvotes: 2