Decimal vs float

Steve Holden steve at holdenweb.com
Thu Jan 19 06:49:42 EST 2006


Kay Schluehr wrote:
> I wonder why this expression works:
> 
> 
>>>>decimal.Decimal("5.5")**1024
> 
> Decimal("1.353299876254915295189966576E+758")
> 
> 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 Decimal type can represent a larger range of values than the 
float type. Your first expression give a Decimal result, your second 
attempts to give a float result.

> 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.
> 
Indeed, as the documentation says: """This serves as an explicit 
reminder of the details of the conversion (including representation 
error)""". Otherwise you would get numpties using constructions like 
Decimal(0.1) and then asking why the result was the same as 
Decimal("0.10000000000000001") (or something similar). Who needs it? 
Certainly not Mr. interpreter, or his c.l.py friends.

> Instead of dealing with awkward wrappers, I wonder if literals
> currently interpreted as floats could not be interpreted as Decimal
> objects in future?
> 
That would be a very large change in the behaviour of the interpreter, 
and unfortunately it doesn't take account of the need in decimal to 
specify the context in which a calculation takes place.You need to be 
able to specify precision, rounding and a number of other values to make 
your computations completely specified. What would you use as the 
default context?

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC                     www.holdenweb.com
PyCon TX 2006                  www.python.org/pycon/




More information about the Python-list mailing list