How to Compare Numbers with Precision in Python?

When comparing numbers with precision in Python, it’s important to consider the potential floating-point rounding errors. One common approach is to use a tolerance or delta value to account for small differences due to floating-point arithmetic. Here’s an example of how you can compare numbers with precision:

def are_close(a, b, rel_tol=1e-9, abs_tol=0.0):
"""Check if two numbers are close within a given tolerance."""
return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)

# Example usage
num1 = 0.1 + 0.1 + 0.1
num2 = 0.3

if are_close(num1, num2):
print("The numbers are close.")
else:
print("The numbers are not close.")

In this example, we define the are_close() function to compare two numbers (a and b) with a relative tolerance (rel_tol) and an absolute tolerance (abs_tol). The function uses the abs() function to calculate the absolute difference between the two numbers and compares it against the larger of the two numbers multiplied by the relative tolerance. If the absolute difference is less than or equal to this value or falls within the absolute tolerance, the numbers are considered close.

The default values for rel_tol and abs_tol in the example are 1e-9 and 0.0 respectively, but you can adjust these values based on your specific requirements.

By using the are_close() function (or a similar approach), you can compare numbers with a desired precision, taking into account potential floating-point errors. It’s important to choose appropriate tolerance values based on the desired level of precision and the magnitude of the numbers being compared.