What is math.isclose in Python: Explanation and Example
math.isclose is a function in Python that checks if two numbers are close to each other within a small tolerance. It helps compare floating-point numbers safely by allowing a tiny difference instead of requiring exact equality.How It Works
Imagine you want to compare two numbers, like 0.1 + 0.2 and 0.3, but because of how computers handle decimals, they might not be exactly equal. math.isclose helps by checking if these numbers are "close enough" instead of exactly the same.
It uses two ways to decide closeness: a relative tolerance and an absolute tolerance. The relative tolerance looks at how big the numbers are and allows a small percentage difference. The absolute tolerance is a fixed small number that works well when numbers are very close to zero.
This way, math.isclose acts like a smart friend who understands small rounding errors and says, "Yes, these numbers are close enough to be considered equal."
Example
This example shows how math.isclose compares two numbers that look equal but are not exactly the same due to floating-point math.
import math num1 = 0.1 + 0.2 num2 = 0.3 print("num1 == num2:", num1 == num2) # Direct equality check print("math.isclose(num1, num2):", math.isclose(num1, num2)) # Close enough check
When to Use
Use math.isclose when you need to compare decimal numbers that might have tiny differences due to rounding or calculation limits. This is common in scientific calculations, financial software, or any program dealing with measurements.
For example, if you calculate distances, weights, or prices that come from different sources or formulas, math.isclose helps avoid errors caused by tiny mismatches.
Key Points
math.isclosecompares two numbers with a tolerance for small differences.- It uses relative and absolute tolerance to decide if numbers are close.
- It is safer than using == for floating-point numbers.
- You can adjust tolerances with
rel_tolandabs_tolparameters.