Introduction
In this lab, you will learn how to check if a number is close to another in Python, addressing the challenges of floating-point number comparisons. You'll start by understanding the concept of numeric proximity and its importance due to the way computers represent floating-point numbers, which can lead to unexpected results when comparing them for equality. A Python script will illustrate this concept by calculating 0.1 + 0.2 and comparing the result to 0.3, demonstrating the potential for inequality due to floating-point representation.
The lab will then guide you through calculating the absolute difference between two numbers as one approach to determining proximity. Finally, you will learn how to use the math.isclose() function for more robust comparisons of floating-point numbers, taking into account both relative and absolute tolerances.
Understand Numeric Proximity
In this step, we will explore the concept of numeric proximity and its importance in programming, especially when dealing with floating-point numbers. Due to the way computers represent floating-point numbers, they are often approximations of real numbers. This can lead to unexpected results when comparing them for equality.
Numeric proximity helps us determine if two numbers are "close enough" to be considered equal, even if they are not exactly the same. This is particularly useful when dealing with calculations that involve floating-point arithmetic.
Let's start by creating a Python script to illustrate this concept.
Open the VS Code editor in the LabEx environment.
Create a new file named
proximity.pyin the~/projectdirectory.~/project/proximity.pyAdd the following code to
proximity.py:## proximity.py num1 = 0.1 + 0.2 num2 = 0.3 print(f"num1 is: {num1}") print(f"num2 is: {num2}") if num1 == num2: print("num1 and num2 are equal") else: print("num1 and num2 are not equal")This script calculates
0.1 + 0.2and compares the result to0.3.Save the file and run it using the following command in the terminal:
python ~/project/proximity.pyYou should see output similar to this:
num1 is: 0.30000000000000004 num2 is: 0.3 num1 and num2 are not equalAs you can see,
num1andnum2are not exactly equal due to floating-point representation, even though mathematically they should be. This is where the concept of numeric proximity becomes important. In the next steps, we will explore ways to handle this situation.
Calculate Absolute Difference
In this step, we will learn how to calculate the absolute difference between two numbers. The absolute difference is the magnitude of the difference between two numbers, regardless of their order. In other words, it's the positive difference between two numbers.
We can use the abs() function in Python to calculate the absolute difference. The abs() function returns the absolute value of a number.
Let's modify the proximity.py script from the previous step to calculate the absolute difference between num1 and num2.
Open the
proximity.pyfile in the~/projectdirectory using the VS Code editor.Modify the code to calculate the absolute difference:
## proximity.py num1 = 0.1 + 0.2 num2 = 0.3 print(f"num1 is: {num1}") print(f"num2 is: {num2}") absolute_difference = abs(num1 - num2) print(f"The absolute difference between num1 and num2 is: {absolute_difference}") if absolute_difference < 0.00001: ## Using a small tolerance print("num1 and num2 are approximately equal") else: print("num1 and num2 are not approximately equal")In this code, we calculate the absolute difference between
num1andnum2using theabs()function. We then compare the absolute difference to a small tolerance value (0.00001 in this case). If the absolute difference is less than the tolerance, we consider the numbers to be approximately equal.Save the file and run it using the following command in the terminal:
python ~/project/proximity.pyYou should see output similar to this:
num1 is: 0.30000000000000004 num2 is: 0.3 The absolute difference between num1 and num2 is: 4.440892098500626e-17 num1 and num2 are approximately equalNow, the script correctly identifies that
num1andnum2are approximately equal by considering the absolute difference and a tolerance value. This approach is more robust than directly comparing floating-point numbers for equality.
Use math.isclose() for Floats
In this step, we will learn how to use the math.isclose() function to compare floating-point numbers for approximate equality. The math.isclose() function is a more robust and recommended way to compare floating-point numbers than using a fixed tolerance.
The math.isclose() function takes two numbers as input and returns True if they are close to each other within a specified tolerance, and False otherwise. It provides two tolerance parameters: rel_tol (relative tolerance) and abs_tol (absolute tolerance).
Let's modify the proximity.py script from the previous step to use the math.isclose() function.
Open the
proximity.pyfile in the~/projectdirectory using the VS Code editor.Modify the code to use
math.isclose():## proximity.py import math num1 = 0.1 + 0.2 num2 = 0.3 print(f"num1 is: {num1}") print(f"num2 is: {num2}") if math.isclose(num1, num2): print("num1 and num2 are approximately equal") else: print("num1 and num2 are not approximately equal")In this code, we import the
mathmodule and use themath.isclose()function to comparenum1andnum2. We use the default values forrel_tolandabs_tol, which are suitable for most cases.Save the file and run it using the following command in the terminal:
python ~/project/proximity.pyYou should see output similar to this:
num1 is: 0.30000000000000004 num2 is: 0.3 num1 and num2 are approximately equalThe script now correctly identifies that
num1andnum2are approximately equal using themath.isclose()function. This is the recommended way to compare floating-point numbers for approximate equality in Python.
Summary
In this lab, we began by exploring the concept of numeric proximity and its importance when comparing floating-point numbers in Python. Due to the way computers represent these numbers, direct equality comparisons can be unreliable. We created a proximity.py script to demonstrate this issue, where 0.1 + 0.2 was compared to 0.3, revealing that they are not exactly equal due to floating-point representation.
The lab then introduced the need for alternative methods to determine if two numbers are "close enough" to be considered equal, setting the stage for exploring techniques like calculating the absolute difference in subsequent steps (content truncated).



