Code:
a = 0.1
b = 0.2
c = 0.3
print(a + b == c)
Solution and Explanation:
The code snippet:
a = 0.1
b = 0.2
c = 0.3
print(a + b == c)
produces False as output. This result can be surprising, but it stems from the way floating-point numbers are represented in computer hardware. Here’s a detailed explanation:
Floating-Point Representation
Binary Representation:
Computers represent floating-point numbers in binary (base-2) format, which can lead to precision issues because not all decimal fractions can be represented exactly as binary fractions.
For example, 0.1 in binary is an infinitely repeating sequence: 0.00011001100110011....
Precision Limitations:
When 0.1 and 0.2 are stored in a computer's memory, they are approximated to the nearest value that can be represented in the finite number of bits available.
The same approximation happens for 0.3.
Summation Inaccuracy:
When adding 0.1 and 0.2, the result is not exactly 0.3 due to these approximations. Instead, the result is a value very close to 0.3, but not exactly 0.3.
The actual value of a + b might be something like 0.30000000000000004.
Comparison:
When Python compares a + b to c, it is comparing 0.30000000000000004 (the result of a + b) to 0.3 (the stored value of c), and since these are not exactly equal, the comparison returns False.
Demonstration with More Precision
You can observe this behavior by printing the values with higher precision:
print(f"{a + b:.17f}") # Shows the precision error
print(f"{c:.17f}")
This will output:
0.30000000000000004
0.29999999999999999
As you can see, the two numbers are very close but not exactly the same, which explains why the comparison a + b == c evaluates to False.
Best Practices
To avoid issues with floating-point comparisons:
Use a Tolerance:
Instead of direct comparison, use a small tolerance value to check if the numbers are "close enough":
tolerance = 1e-10
print(abs((a + b) - c) < tolerance) # True
Decimal Module:
For financial and other high-precision calculations, use Python's decimal module which can handle decimal arithmetic more accurately.
from decimal import Decimal
a = Decimal('0.1')
b = Decimal('0.2')
c = Decimal('0.3')
print(a + b == c) # True
This approach avoids the pitfalls of floating-point arithmetic by using a representation that can exactly represent decimal fractions.
0 Comments:
Post a Comment