imprecision in float in python

Viewed 33

first post here. I'm a CS50 student and i'm on my first python pset. I'm writing cash and this is my code:

from cs50 import get_float

while True:
    cents = get_float("Change owed?: ")
    if cents > 0:
        break
counter = 0
while cents >= 0.25:
    cents = cents - 0.25
    counter += 1
while cents >= 0.10:
    cents = cents - 0.10
    counter += 1
while cents >= 0.05:
    cents = cents - 0.05
    counter += 1
while cents >= 0.01:
    cents = cents - 0.01
    counter += 1
print(f"{counter}")

the program doesn't print the correct results, so i run the debugger and i found out that when the program goes from counting 0.10 to 0.05 the cents counter gets imprecise (for example if i wrote 0.41 the first cycle returns 0.16 meanwhile the second 0.5999 instead of 0.6 and so the program always skip something, because the value is not correct). I hope i've been somewhat clear. I'll probably use a round function to solve my problem, but i was curious to understand why python is imprecise here.

0 Answers
Related