Dividing decimals yields invalid results in Python 2.5 to 2.7
After a very thorough read of the Python's decimal module documentation, I still find myself puzzled by what happens when I divide a decimal.
In Python 2.4.6 (makes sense):
>>> import decimal
>>> decimal.Decimal(1000) / 10
Decimal("100")
In Python 2.5.6, Python 2.6.7, and Python 2.7.2 (puzzling):
>>> import decimal
>>> decimal.Decimal(1000) / 10
Decimal('0.00000-6930898827444486144')
More confusing yet, that result doesn't even appear to be valid:
>>> decimal.Decimal('0.00000-6930898827444486144')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/decimal.py", line 548, in __new__
"Invalid literal for Decimal: %r" % value)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/decimal.py", line 3844, in _raise_error
raise error(explanation)
decimal.InvalidOperation: Invalid开发者_JAVA技巧 literal for Decimal: '0.00000-6930898827444486144'
The result is the same using decimal.Decimal(1000) / decimal.Decimal(10)
, so it's not an issue with using an int as the divisor.
Part of the issue is clearly around precision:
>>> decimal.Decimal("1000.000") / decimal.Decimal("10.000")
Decimal('0.00000-6930898827444486144')
>>> decimal.Decimal("1000.000") / decimal.Decimal("10")
Decimal('0.000200376420520689664')
But there should be ample precision in decimal.Decimal("1000.000")
to divide safely by 10 and get an answer that's at least in the right ballpark.
The fact that this behavior is unchanged through three major revisions of Python says to me that it is not a bug.
What am I doing wrong? What am I missing?
How can I divide a decimal (short of using Python 2.4)?
From your MacPorts bug, you have installed Xcode 4 and your version of Python 2.7.2 was built with the clang C compiler, rather than gcc-4.2. There is at least one known problem with building with clang on OS X that has been fixed in Python subsequent to the 2.7.2. release. Either apply the patch or, better, ensure the build uses gcc-4.2. Something like (untested!):
sudo bash
export CC=/usr/bin/gcc-4.2
port clean python27
port upgrade --force python27
prior to the build might work if MacPorts doesn't override it.
UPDATE: The required patch has now been applied to the MacPorts port files for Python 2. See https://trac.macports.org/changeset/87442
Just for the record: For python 2.7.3 compiled with clang (via Homebrew on OS X), this seems to be fixed.
Python 2.7.3 (default, Oct 10 2012, 13:00:00)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import decimal
>>> decimal.Decimal(1000) / 10
Decimal('100')
精彩评论