Python -- floating point arithmetic

Zooko O'Whielacronx zooko at zooko.com
Thu Jul 8 12:38:24 EDT 2010


On Thu, Jul 8, 2010 at 4:58 AM, Adam Skutt <askutt at gmail.com> wrote:
>
> I can't think of any program I've ever written where the inputs are
> actually intended to be decimal.  Consider a simple video editing
> program, and the user specifies a frame rate 23.976 fps.  Is that what
> they really wanted?  No, they wanted 24000/1001 but didn't feel like
> typing that.

Okay, so there was a lossy conversion from the user's intention
(24000/1001) to what they typed in (23.976).

>>> instr = '23.976'

Now as a programmer you have two choices:

1. accept what they typed in and losslessly store it in a decimal:

>>> from decimal import Decimal as D
>>> x = D(instr)
>>> print x
23.976

2. accept what they typed in and lossily convert it to a float:

>>> x = float(instr)
>>> print "%.60f" % (x,)
23.975999999999999090505298227071762084960937500000000000000000

option 2 introduces further "error" between what you have stored in
your program and what the user originally wanted and offers no
advantages except for speed, right?

>> I'm sorry, what will never be true? Are you saying that decimals have
>> a disadvantage compared to floats? If so, what is their disadvantage?
>
> He's saying that once you get past elementary operations, you quickly
> run into irrational numbers, which you will not be representing
> accurately.  Moreover, in general, it's impossible to even round
> operations involving transcendental functions to an arbitrary fixed-
> precision, you may need effectively infinite precision in order to the
> computation.  In practice, this means the error induced by a lossy
> input conversion (assuming you hadn't already lost information) is
> entirely negligible compared to inherent inability to do the necessary
> calculations.

But this is not a disadvantage of decimal compared to float is it?
These problems affect both representations. Although perhaps they
affect them differently, I'm not sure.

I think sometimes people conflate the fact that decimals can easily
have higher and more variable precision than floats with the fact that
decimals are capable of losslessly storing decimal values but floats
aren't.

Regards,

Zooko



More information about the Python-list mailing list