Python: change calculator

Python: change calculator

The problem is in the second step. If you start with 1.95, step one returns 7 quarters with a remainder of $0.20. So money2 is now 0.20. Now we divide by the value of a dime. Because of floating point error our result is likely not an even 2 but more like 1.9999999. Python 2.7s int() method rounds towards zero so this gets rounded to 1 dime. The remainder is $0.10 and this gets divided by the value of a nickle which leads to the same problem but this time it rounds down to one nickle.

To fix this, I recommend using an integer number of pennies instead of a floating point value representing dollars.

So, 1.95 becomes 195 and the values of a quarter, a dime, and a nickle are 25, 10, and 5, respectively.

Edit Try this:

x = raw_input(Please enter an amount of change (in pennies))
x = int(x)
q = 25
d = 10
n = 5
numberQ = (x - (x % q))/q
money2 = x % q
numberD = (money2 - (money2 % d))/d
money3 = money2 % d
numberN = (money3 - (money3 % n))/n
pennies = money3 % n
print numberQ
print numberD
print numberN
print pennies

The % gives the remainder of an integer division. If we subtract the remainder from the amount we started with and divide that by the coin value we know the result will be a whole integer. The remainder becomes the new amount of money.

It is due to float not precisely holding the values.

>>> money2/d
1.9999999999999996

Try multiplying everything by 100:

x = float(195)
q = float(25)
d = float(10)
n = float(5)
numberQ = x/q
numberQ = int(numberQ)
money2 = x - (numberQ * q)
numberD = money2/d
numberD = int(numberD)
money3 = money2 - (numberD * d)
numberN = money3/n
numberN = int(numberN)
print numberQ
print numberD
print numberN

Online Example

Edit: You could also use the decimal package to do this:

from decimal import Decimal
x = Decimal(1.95)
q = Decimal(.25)
d = Decimal(.10)
n = Decimal(.05)
numberQ = x/q
numberQ = int(numberQ)
money2 = x - (numberQ * q)
numberD = money2/d
numberD = int(numberD)
money3 = money2 - (numberD * d)
numberN = money3/n
numberN = int(numberN)
print numberQ
print numberD
print numberN

Python: change calculator

You appear to be running into floating point precision errors; for example, after running your code in IDLE, requesting money2 and money3 gives these values:

>>> money2
0.19999999999999996
>>> money3
0.09999999999999995

Computerphile has a good video on this here, if you would like to learn more. Apart from that, try converting it so that money is represented by an integer number of cents; i.e. $1.95 would be 195.

Good luck.

Leave a Reply

Your email address will not be published. Required fields are marked *