During pset6/cash, I tried to write the python code without multiplying change by 100 to get cents (as I had in c).

I had assumed that this wouldn't lead to any precision issues, however when inputting change as 0.15 and running debug50, I can see that change goes to 0.0499999999999999 after subtracting a dime.

Please can someone explain the mechanism behind this?

Many thanks in advance!

Code is below:

from cs50 import get_float

change = get_float("Change owed: ")
while change < 0:
    change = get_float("Change owed: ")

coin_counter = 0

while change >= 0.25:
    change = change - 0.25
    coin_counter += 1

while change >= 0.1:
    change = change - 0.1
    coin_counter += 1

while change >= 0.05:
    change = change - 0.05
    coin_counter += 1

while change >= 0.01:
    change = change - 0.01
    coin_counter += 1


There is not really a mechanism to describe. Floats are only so precise, and so performing mathematical operations with them will result in some imprecision in results. I'll keep this discussion to Python, since it has different data types than C-based languages. It is important to remember that floats are approximations of fractions, and that these approximations are rarely 100% accurate to their fractional counterpart; the computer uses base-2, while we use base-10, and most fractions do not convert smoothly between the two. This becomes even more of an issue when mathematical operations are applied to fractions, especially to more than one of them. Python will provide an approximation of the values that the computer has stored/computed when displaying a float value. Even if it looks to be a perfectly precise decimal value, it is important to remember that such is not always, if ever, the case.

I recommend reading up on the Python documentation on this topic, as the same issue will apply no matter what language you are working with (thought different languages have different methods of dealing with it). Ultimately, the solution is not "how can I prevent this from happening," but "how can I ensure I get a value to my desired precision?" It sounds like you possibly solved this in your C version by turning the values into ints, which do not have this issue as those can be converted between base-2 and base-10 by the computer with ease.

Hope this helps clear things up for you. :) If it does, feel free to accept the answer with the check. But, if not, feel free to leave me a comment and I'll do my best to provide some more help.

  • Thanks Robert, very helpful! – Tim Swinn Mar 3 at 14:46

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .