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.