浮点数超大数值处理及除法结果相等性比较异常问题咨询
It’s a classic floating-point precision gotcha! Let’s break down exactly what’s happening here and how to fix it.
The Root Cause
Floating-point numbers (like Python’s float) rely on binary representation, which can’t perfectly capture every decimal fraction—especially extremely small or large values. Here’s the step-by-step breakdown:
- Your tiny denominator isn’t exact: When you write
0.00000000000000000000007, Python converts this to the closest possible 64-bit float. That stored value is actually slightly larger than the exact7e-23you intended. - Division gives a near-but-not-exact result: Dividing
7by this approximated denominator produces a value that’s very close to1e+23, but not exactly equal to the literal1e+23or your variablett(which holds the exact float representation of1e+23). - String output hides the difference: When printed, Python rounds floats to a human-readable 15 significant digits. Both values look like
1e+23in output, but their underlying binary values are subtly different.
To confirm this, let’s peek at the exact values using Python’s decimal module:
import decimal # Exact value of your tiny denominator as a float print(decimal.Decimal(0.00000000000000000000007)) # Output: 7.00000000000000020816681711721685132943093776702880859375E-23 # Exact value of temp_ans temp_ans = 7 / 0.00000000000000000000007 print(decimal.Decimal(temp_ans)) # Output: 99999999999999991611392.0 # Exact value of 1e+23 as a float print(decimal.Decimal(1e+23)) # Output: 100000000000000000000000.0
As you can see, temp_ans is a tiny bit smaller than 1e+23—which is why the equality checks fail.
How to Fix This
Instead of checking for exact equality with ==, compare if the values are within a small tolerance (called epsilon) of each other. This is the standard practice for floating-point comparisons.
Example:
temp_ans = 7 / 0.00000000000000000000007 tt = 1e+23 # Choose a small epsilon (adjust based on your precision needs) epsilon = 1e-9 if abs(tt - temp_ans) < epsilon: print("YES1") if abs(1e+23 - temp_ans) < epsilon: print("YES2") if tt == 1e+23: print("YES3")
This will output all three "YES" messages as you expected.
Alternatively, if you need precise decimal arithmetic (no floating-point approximations), use Python’s decimal module to work with exact decimal values instead of floats.
内容的提问来源于stack exchange,提问作者Rahul Verma

