簡體   English   中英

"Python Decimal 模塊不適用於 uint64"

[英]Python Decimal module doesn't work on uint64

我正在嘗試將 numpy.uint64(由 numpy.sum() 輸出)轉換為小數,而不會丟失 Decimal 模塊的精度。

>>> from decimal import Decimal
>>> import numpy as np
>>>
>>> sum = np.sum(1000000000000000000)
>>> type(sum)
<type 'numpy.int64'>
>>> Decimal(sum)
Decimal('1000000000000000000')
>>>
>>> sum = np.sum(1000000000000000000000)
>>> type(sum)
<type 'long'>
>>> Decimal(sum)
Decimal('1000000000000000000000')
>>>
>>> sum = np.sum(10000000000000000000)
>>> type(sum)
<type 'numpy.uint64'>
>>> Decimal(sum)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/decimal.py", line 657, in __new__
    raise TypeError("Cannot convert %r to Decimal" % value)
TypeError: Cannot convert 10000000000000000000 to Decimal

decimal.Decimal無法理解NumPy輸入,因此請在調用decimal.Decimal之前,使用item方法numpy.uint64轉換為Python標量:

Decimal(np.sum(whatever).item())

就我而言,剛剛從熊貓0.20.3升級到0.21修復了它

您還可以在轉換為十進制之前將其轉換為浮點數:

Decimal(float(sum))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM