2012-03-10 58 views
9

我想讀的財務數據和存儲。我從商店獲取財務數據的地方以令人難以置信的精度存儲數據,但我只對小數點後的5位數字感興趣。因此,我決定用T = .quantize(cdecimal.Decimal(」 00001' ),四捨五入= cdecimal.ROUND_UP)在小數我創造的,但我不斷收到InvalidOperation異常。爲什麼是這樣?Python的cdecimal InvalidOperation

>>> import cdecimal 
>>> c = cdecimal.getcontext() 
>>> c.prec = 5 
>>> s = '45.2091000080109' 
>>> # s = '0.257585003972054' works! 
>>> t = cdecimal.Decimal(s).quantize(cdecimal.Decimal('.00001'), rounding=cdecimal.ROUND_UP) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    cdecimal.InvalidOperation: [<class 'cdecimal.InvalidOperation'>] 

爲什麼在這裏出現無效操作?如果我將精度更改爲7(或更高),它將起作用。如果我將s設置爲'0.257585003972054'而不是原始值,那也行!到底是怎麼回事?

謝謝!

回答

12

小數點的版本給出了錯誤的更好的描述:

Python 2.7.2+ (default, Feb 16 2012, 18:47:58) 
>>> import decimal 
>>> s = '45.2091000080109' 
>>> decimal.getcontext().prec = 5 
>>> decimal.Decimal(s).quantize(decimal.Decimal('.00001'), rounding=decimal.ROUND_UP) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/usr/lib/python2.7/decimal.py", line 2464, in quantize 
    'quantize result has too many digits for current context') 
    File "/usr/lib/python2.7/decimal.py", line 3866, in _raise_error 
    raise error(explanation) 
decimal.InvalidOperation: quantize result has too many digits for current context 
>>> 

Docs

Unlike other operations, if the length of the coefficient after the quantize operation would be greater than precision, then an InvalidOperation is signaled. This guarantees that, unless there is an error condition, the quantized exponent is always equal to that of the right-hand operand.

但我必須承認,我不知道這意味着什麼。

+12

的問題是背景中的「PREC」並不意味着你和/或OP覺得這意味着什麼。這是總精度,而不是「小數點後的精度」。 1.2345具有五位精度,123.45也是如此,但123.45000具有八位,而不是五位精度。 – torek 2012-03-10 21:26:39

+1

謝謝 - 這使!有沒有辦法在小數點之後爲分割操作設置一個精度? – user1094786 2012-03-10 21:32:22

+1

只有.quantize()。爲了做到科學記數法的精確度,這是一個痛苦,但對於你的情況很簡單,你只需測量0.00001。 :-) – torek 2012-03-10 22:00:25