"""
====================================================================
Title: Safe Floating-Point Comparison in Python
Purpose:
Demonstrates the recommended way to compare floating-point
values safely using math.isclose().
Why not use == ?
Floating-point numbers are stored as binary approximations.
Many decimal values cannot be represented exactly, which can
result in tiny rounding errors.
Example:
0.1 + 0.2 != 0.3
Although mathematically equal, the actual stored values
differ slightly.
====================================================================
"""
import math
def approximately_equal(a, b,
rel_tolerance=1e-9,
abs_tolerance=1e-12):
"""
Safely compares two floating-point values.
Parameters:
a (float): First value
b (float): Second value
rel_tolerance (float):
Relative tolerance for larger numbers
abs_tolerance (float):
Absolute tolerance for values near zero
Returns:
bool:
True if values are considered equal,
otherwise False
Best Practice:
Use math.isclose() instead of manually checking
abs(a - b) <= epsilon whenever possible.
"""
return math.isclose(
a,
b,
rel_tol=rel_tolerance,
abs_tol=abs_tolerance
)
def main():
"""
Demonstrates safe floating-point comparison.
"""
# Classic floating-point precision example
x = 0.1 + 0.2
y = 0.3
print("=" * 60)
print(" Safe Floating-Point Comparison in Python")
print("=" * 60)
print()
# Display many decimal places to expose
# floating-point representation differences.
print(f"x = {x:.17f}")
print(f"y = {y:.17f}")
print()
# ---------------------------------------------------------
# BAD PRACTICE:
# Direct comparison using ==.
#
# This may fail due to tiny rounding differences.
# ---------------------------------------------------------
if x == y:
print("Direct comparison (==): Equal")
else:
print("Direct comparison (==): Not Equal")
print()
# ---------------------------------------------------------
# GOOD PRACTICE:
# Use a tolerance-based comparison.
# ---------------------------------------------------------
if approximately_equal(x, y):
print("math.isclose(): Equal")
else:
print("math.isclose(): Not Equal")
if __name__ == "__main__":
main()
'''
run:
============================================================
Safe Floating-Point Comparison in Python
============================================================
x = 0.30000000000000004
y = 0.29999999999999999
Direct comparison (==): Not Equal
math.isclose(): Equal
'''