Explore Floating-Point Representation
In this step, you will explore how floating-point numbers are represented in Python and the potential implications this representation can have on numerical comparisons. Floating-point numbers are used to represent real numbers (numbers with decimal points) in computers. However, due to the way they are stored in memory, they are often approximations of the actual real numbers. This can lead to unexpected results when performing comparisons.
Let's start by creating a Python file named float_representation.py
in your ~/project
directory using the VS Code editor.
## Create a floating-point number
x = 0.1 + 0.2
## Print the value of x
print(x)
Save the file and then execute it using the following command in the terminal:
python float_representation.py
You might expect the output to be 0.3
, but you'll likely see something like this:
0.30000000000000004
This is because 0.1
and 0.2
cannot be represented exactly as floating-point numbers. The result of the addition is a number that is very close to 0.3
, but not exactly equal to it.
Now, let's see how this imprecision can affect comparisons. Add the following code to your float_representation.py
file:
## Create a floating-point number
x = 0.1 + 0.2
## Check if x is equal to 0.3
if x == 0.3:
print("x is equal to 0.3")
else:
print("x is not equal to 0.3")
Save the file and run it again:
python float_representation.py
You will likely see the following output:
x is not equal to 0.3
This is because x
is not exactly equal to 0.3
due to the floating-point representation issue.
To compare floating-point numbers accurately, you should use a tolerance value. Instead of checking for exact equality, check if the absolute difference between the two numbers is less than a small tolerance value.
Modify your float_representation.py
file to include a tolerance:
## Create a floating-point number
x = 0.1 + 0.2
## Define a tolerance value
tolerance = 1e-9 ## A small value like 0.000000001
## Check if x is approximately equal to 0.3
if abs(x - 0.3) < tolerance:
print("x is approximately equal to 0.3")
else:
print("x is not approximately equal to 0.3")
Save the file and run it one more time:
python float_representation.py
Now, you should see the following output:
x is approximately equal to 0.3
By using a tolerance, you can accurately compare floating-point numbers despite the inherent imprecision in their representation. This is a crucial concept to understand when working with floating-point numbers in Python and other programming languages.