Python float Lab
Lab: The Floating-Point Trap
Try running this in your Python terminal to see the logic gap:
-
Step 1: Calculate
0.1 + 0.2. -
Step 2: Compare it to
0.3. -
Step 3: Use the
decimalmodule to see the "true" value.
Python
import decimal
# The Trap
print(0.1 + 0.2 == 0.3) # Result: False
# The Reality
print(decimal.Decimal(0.1))
# You will see: 0.1000000000000000055511151231257827021181583404541015625
Lab: Basics & Type Conversion
Task:
Calculate the total and print its type.
Create a variable price with the value 19.99.
Convert the integer 5 to a float and store it in quantity.
import math
price = 19.99
quantity = float(5)
total = price * quantity
print(f"Total: {total}, Type: {type(total)}")
# Output: Total: 99.95, Type:
Lab: Precision & Rounding
Use a built-in function to round result to 2 decimal places.
Calculate $0.1 + 0.2$ and store it in result.
Print result. (Note: Observe if it is exactly 0.3).
import math
result = 0.1 + 0.2
print(f"Raw result: {result}")
# Output: 0.30000000000000004 (Due to binary floating-point representation)
rounded_result = round(result, 2)
print(f"Rounded: {rounded_result}")
Why does 0.1 + 0.2 not equal 0.3?
In Python (and most programming languages), floats are represented in binary (base-2). Just as the fraction 1/3 cannot be perfectly represented in decimal (it's 0.3333...), the fraction 1/10 (0.1) cannot be perfectly represented in binary. This leads to the tiny "overflow" you see in the raw result.
Lab: Formatting Output
Task:
Given pi_approx = 22 / 7, print the value formatted to exactly 3 decimal places using an f-string.
import math
pi_approx = 22 / 7
print(f"Pi to 3 decimal places: {pi_approx:.3f}")
Lab: The math Module
Task:
Use math.isclose() to check if 0.1 + 0.2 is effectively equal to 0.3.
Import the math module.
Use math.floor() and math.ceil() on the number 4.7.
import math
val = 4.7
print(f"Floor: {math.floor(val)}") # 4
print(f"Ceil: {math.ceil(val)}") # 5
# Checking equality for floats
comparison = math.isclose(0.1 + 0.2, 0.3)
print(f"Is 0.1 + 0.2 close to 0.3? {comparison}")
Lab: The Initialization
Goal: Create a script that handles user input for a grocery store.
-
Ask the user for the
priceof an item (e.g., 2.50). -
Ask for the
quantity(e.g., 3). -
Calculate the total. Even if the user enters "3", ensure the calculation treats it as a float.
-
Bonus: Print the memory address of the float variable using
id().
import math
# Using float() to wrap input ensures we don't get a string error
price = float(input("Enter price: ")) # User enters 2.5
quantity = float(input("Enter quantity: ")) # User enters 3
total = price * quantity
print(f"Total: {total}") # Output: 7.5
print(f"Memory ID: {id(total)}")
Lab:
The Precision Paradox
Goal: Demonstrate why developers never use floats for financial calculations.
-
Add
0.1and0.2. -
Compare the result to
0.3using the==operator. -
Explain why the result is
Falseusing a comment.
import math
result = 0.1 + 0.2
print(f"0.1 + 0.2 is {result}")
# Result: 0.30000000000000004
print(result == 0.3) # Output: False
# Fix: Use math.isclose for floating point comparison
print(math.isclose(result, 0.3)) # Output: True
Lab:
Advanced Rounding
Goal: Explore the math module.
-
Given
val = 12.51, use three different methods to turn it into a whole number: -
math.floor() -
math.ceil() -
int()conversion. -
Observe how they differ for the same value.
import math
val = 12.51
print(math.floor(val)) # 12 (Down to nearest integer)
print(math.ceil(val)) # 13 (Up to nearest integer)
print(int(val)) # 12 (Truncates everything after decimal)
Lab:
Scientific Notation & Large Numbers
Goal: Work with very small and very large floats.
-
Create a variable
atomsequal to 6.022×1023. -
Create a variable
sizeequal to 0.000000005. -
Print them and see how Python automatically formats them.
import math
### Solution 4: Scientific Notation
atoms = 6.022e23
size = 5e-9
print(atoms) # 6.022e+23
print(size) # 5e-09
Lab:
The "Boss Level" Precision (The decimal Module)
Goal: Fix the floating-point error from Challenge 2 using Python's decimal module.
-
Import
Decimal