4 hundred quadrillonth?

Chris Rebert clp2 at rebertia.com
Fri May 22 00:36:07 CEST 2009


On Thu, May 21, 2009 at 2:53 PM, Carl Banks <pavlovevidence at gmail.com> wrote:
> On May 21, 2:05 pm, seanm... at gmail.com wrote:
>> The explaination in my introductory Python book is not very
>> satisfying, and I am hoping someone can explain the following to me:
>>
>> >>> 4 / 5.0
>>
>> 0.80000000000000004
>>
>> 4 / 5.0 is 0.8. No more, no less.
>
> That would depend on how you define the numbers and division.
>
> What you say is correct for real numbers and field division.  It's not
> true for the types of numbers Python uses, which are not real numbers.
>
> Python numbers are floating point numbers, defined (approximately) by
> IEEE 754, and they behave similar to but not exactly the same as real
> numbers.  There will always be small round-off errors, and there is
> nothing you can do about it except to understand it.
>
>
>> It bothers me.
>
> Oh well.
>
> You can try Rational numbers if you want, I think they were added in
> Python 2.6.  But if you're not careful the divisors can get
> ridiculously large.

The `decimal` module's Decimal type is also an option to consider:

Python 2.6.2 (r262:71600, May 14 2009, 16:34:51)
>>> from decimal import Decimal
>>> Decimal(4)/Decimal(5)
Decimal('0.8')

Cheers,
Chris
-- 
http://blog.rebertia.com



More information about the Python-list mailing list