Reputation: 471
I am working on some scripts that handle calculation with the need of maintaining high accuracy of the results so I started using decimal.Decimal instead of built-in float.
I know it doesn't work with float-type values and it returns TypeError: unsupported operand type(s) for +: 'decimal.Decimal' and 'float' What I need to know exactly is why it doesn't support this type of operations with float.
Sample:
from decimal import Decimal
expr_= 1.2+Decimal('1')
As this seems logic for me when I try to add str to float to get this type of error but not while trying to calculate two numeric values.
While I can easily do the same thing using SymPy Float data-type without facing any issues. Ex:
from decimal import Decimal
from sympy import Float
expr_=Decimal('1.6')+Float(1.2)
Upvotes: 3
Views: 2586
Reputation: 879681
PEP 327 -- Decimal Data Type explains:
Aahz is strongly opposed to interact with float, suggesting an explicit conversion:
The problem is that Decimal is capable of greater precision, accuracy, and range than float.
The example of the valid python expression,
35 + 1.1
, seems to suggest thatDecimal(35) + 1.1
should also be valid. However, a closer look shows that it only demonstrates the feasibility of integer to floating point conversions. Hence, the correct analog for decimal floating point is 35 + Decimal(1.1). Both coercions, int-to-float and int-to-Decimal, can be done without incurring representation error.The question of how to coerce between binary and decimal floating point is more complex. I proposed allowing the interaction with float, making an exact conversion and raising ValueError if exceeds the precision in the current context (this is maybe too tricky, because for example with a precision of 9, Decimal(35) + 1.2 is OK but Decimal(35) + 1.1 raises an error).
This resulted to be too tricky. So tricky, that c.l.p agreed to raise TypeError in this case: you could not mix Decimal and float.
This is the python developer's mailing list discussion on the subject. For the full thread, see the 2003-10 archive and search for "Decimal".
So in the end, the "Explicit is better than implicit" philosophy won out.
Upvotes: 4