Decimal vs float
Gerhard Häring
gh at ghaering.de
Thu Jan 19 06:16:22 EST 2006
Kay Schluehr wrote:
> I wonder why this expression works:
>
>>>>decimal.Decimal("5.5")**1024
>
> Decimal("1.353299876254915295189966576E+758")
The result is a Decimal type, which can have *very high* values.
> but this one causes an error
>
> 5.5**1024
>
> Traceback (most recent call last):
> File "<interactive input>", line 1, in ?
> OverflowError: (34, 'Result too large')
Because the result is a float, which values are limited by your hardware
(CPU).
> Another quirk is the follwoing:
>
>
>>>>decimal.Decimal(5.5)
>
> Traceback (most recent call last):
> ...
> TypeError: Cannot convert float to Decimal. First convert the float to
> a string
>
> If Mr. interpreter is as slick as he is why doesn't he convert the
> float by himself? This is at most a warning caused by possible rounding
> errors of float.
floating points are always imprecise, so you wouldn't want them as an
input parameter for a precise Decimal type.
Because if your nice Decimal type would then look like this:
Decimal("5.499999999999999999999999999999999999999999999999999999999999999")
you would complain too, right?
For more enlightenment, you can start with the PEP
http://www.python.org/peps/pep-0327.html#explicit-construction
> Instead of dealing with awkward wrappers, I wonder if literals
> currently interpreted as floats could not be interpreted as Decimal
> objects in future?
No, because a software Decimal type is orders of magnitude slower than
floating point types, for which there is hardware support by your CPU.
If you're asking for additional Python decimal literals like
mydecimal = 5.5d
or whatever, that's a different question. I don't know if anything like
this is planned. FWIW I don't think it's necessary. using the Decimal
constructor is explicit too and we don't really need syntactic sugar for
decimal literals.
-- Gerhard
More information about the Python-list
mailing list