[Tutor] How to correct decimal addition.

spir denis.spir at gmail.com
Sun Jan 26 01:12:56 CET 2014


On 01/25/2014 10:01 PM, Keith Winston wrote:
> On Sat, Jan 25, 2014 at 3:57 AM, spir <denis.spir at gmail.com> wrote:
>>> .009 to the price, so that people do not have to type the full amount.
>>>    Example, 3.49 /gallon would return 3.499 /gallon.
>>>
>>> This is what I have tried and the results of it.
>>>
>>> def gas_price(price):
>>>      price == raw_input("What is the price of gas?")  return price + .09
>>>     3.49=> 3.4899999999999998
>
> I think there's an inconsistency in your post that might confuse the
> answers. You mention in the lead that you want to add 9 ONE HUNDREDTHS
> of a dollar, or tenths of a cent (which is in fact how gas is priced
> in the US, and yes it's crazy stupid). However in your example you add
> only tenths, but then in the answer you appear to have added
> hundredths, which makes me think that you didn't cut & paste, but
> rather retyped (and mistyped).
>
> This will make it a little trickier to use Denis' last idea of using
> integers, since you'll have to take them out one more order of
> magnitude.

I guess this is what I wrote (unit was 1/10 cent), or maybe I misunderstand your 
point.

>  If this exercise is later followed by interest
> calculations, or anything like that, you might regret limiting your
> internal accuracy/representation.
>
> I think that you should probably do your math in floating point (why
> get complicated? And you might need the accuracy, for hundredths of
> dollars and interest) and then format the output to be what you want.
> Watch out for rounding.
>
>>>> p = 3.499
>>>> print('{0:.3f}'.format(p))   # format a float with 3 places after the decimal
> 3.499
>>>> p = 3.4994
>>>> print('{0:.3f}'.format(p))
> 3.499
>>>> p = 3.4999999
>>>> print('{0:.3f}'.format(p))
> 3.500

Yes; but this only corrects output, fo the user's comfort. If you need to do 
further computations, then the internal representation must also be right (else 
you'll get at best rounding errors, at worst worse ;-), and this can only be 
ensured by computing on integers or decimals. Typically, using integers, you'll 
choose a unit a few orders of magnitude lower than the most precise numbers 
possibly involved in computations (eg, a tax rate of 0.1234567 ;-).

d


More information about the Tutor mailing list