How to Check If a Number Is Close to Another in Python

PythonPythonBeginner
Practice Now

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python/BasicConceptsGroup -.-> python/numeric_types("Numeric Types") python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") subgraph Lab Skills python/numeric_types -.-> lab-559546{{"How to Check If a Number Is Close to Another in Python"}} python/conditional_statements -.-> lab-559546{{"How to Check If a Number Is Close to Another in Python"}} python/build_in_functions -.-> lab-559546{{"How to Check If a Number Is Close to Another in Python"}} end

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.

  1. Open the VS Code editor in the LabEx environment.

  2. Create a new file named proximity.py in the ~/project directory.

    ~/project/proximity.py
  3. Add 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.2 and compares the result to 0.3.

  4. Save the file and run it using the following command in the terminal:

    python ~/project/proximity.py

    You should see output similar to this:

    num1 is: 0.30000000000000004
    num2 is: 0.3
    num1 and num2 are not equal

    As you can see, num1 and num2 are 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.

  1. Open the proximity.py file in the ~/project directory using the VS Code editor.

  2. 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 num1 and num2 using the abs() 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.

  3. Save the file and run it using the following command in the terminal:

    python ~/project/proximity.py

    You 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 equal

    Now, the script correctly identifies that num1 and num2 are 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.

  1. Open the proximity.py file in the ~/project directory using the VS Code editor.

  2. 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 math module and use the math.isclose() function to compare num1 and num2. We use the default values for rel_tol and abs_tol, which are suitable for most cases.

  3. Save the file and run it using the following command in the terminal:

    python ~/project/proximity.py

    You should see output similar to this:

    num1 is: 0.30000000000000004
    num2 is: 0.3
    num1 and num2 are approximately equal

    The script now correctly identifies that num1 and num2 are approximately equal using the math.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).