Reputation: 133
I have two float values, I would like to subtract them and compare the result with another value in an if statement. Problem, I didn't manage to have the expected result. I tried to use Decimal module.
from decimal import Decimal, getcontext
getcontext().prec = 3
value_1 = 60.32
value_2 = 59.72
condition = 0.6
sub = Decimal(value_1) - Decimal(value_2)
But,
sub <= condition
FALSE
sub <= Decimal(condition)
FALSE
Upvotes: 0
Views: 1559
Reputation: 51643
This answer explains why this question is a dupe of Is floating point math broken?.
If you use
k = Decimal(0.6)
and inspect k
you get:
This is a case of "Is floating math broken":
0.6
is first converted to a float (wich gives the nearest float-approximation)Decimal
constructor wich dutifully constructs a Decimal
that is just a little bit smaller then the 0.6
originally put in your source code.You can avoid this by providing a string of your number to the decimal constructor instead to bypass the "float"-conversion.
Inspecting
value_1 = 60.32
value_2 = 59.72
sub = Decimal(value_1) - Decimal(value_2)
leads to :
which is exactly 0.6. As k
is now slightly less then 0.6 your test of sub <= k
returns False
.
You can use k = Decimal("0.6")
to get a decimal value that is exactly 0.6.
Upvotes: 1