Further question. If I round the input right at the beginning, round(paid,2) does that mean I still have the original error from using .76 even before math, or does the rounding kill it? I would guess not if it's binary, although Python must have a way to handle money amounts. I'm only on Chapter 2 ;')
I assume Python has some automatic way to filter input, so that if someone entered three decimals instead of two for a money amount, they could get a wrist slap. Can you direct me to that functionality? Thanks. Jim On 16 April 2013 11:55, Sander Sweers <sander.swe...@gmail.com> wrote: > On 04/16/2013 07:48 PM, Jim Mooney wrote: >> I accidentally sent as HTML so this is a resend in case that choked >> the mailing prog ;') >> >> I was doing a simple training prog to figure monetary change, and >> wanted to avoid computer inaccuracy by using only two-decimal input >> and not using division or mod where it would cause error. Yet, on a >> simple subtraction I got a decimal error instead of a two decimal >> result, as per below. What gives? > > Floats can not be represented accurately in binary and will have small > rounding errors. See > https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems. > >> cost = float(input('How much did the item cost?: ')) >> paid = float(input('How much did the customer give you?: ')) >> change = paid - cost >> >> #using 22.89 as cost and 248.76 as paid >> >> twenties = int(change / 20) >> if twenties != 0: >> twentiesAmount = 20 * twenties >> change = change - twentiesAmount >> #change is 5.8700000000000045, not 5.87 - how did I get this decimal >> error when simply subtracting an integer from what should be a >> #two-decimal amount? >> print(twenties, ' twenties') >> print(change) >> >> #and so forth for the rest of the prog > > You can use string formatting to show as much precision you want. Example: > >>>> n = 5.8700000000000045 >>>> print '%.2f' % n > 5.87 >>>> print '%.4f' % n > 5.8700 > > Or use round(), example: > >>>> round(n,2) > 5.87 > > In your case I would just use string formatting to hide the rounding error. > > Greets > ~sander -- Jim Mooney If you shoot a child you're a bad guy. If you splatter forty children across a wall with a bomb, you're a heroic, manly Top Gun with gleaming Tom Cruise teeth. The moral is you'll get laid more if you snuff a lot of children than if you only snuff a few. _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor