Python Decimal模块在uint64上不起作用 [英] Python Decimal module doesn't work on uint64

查看:84
本文介绍了Python Decimal模块在uint64上不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将numpy.uint64(由numpy.sum()输出)转换为小数,而不会损失Decimal模块的精度。

I'm trying to convert a numpy.uint64 (which is outputted by numpy.sum()) to a decimal without losing precision with the Decimal module.

>>> 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 不理解NumPy输入,因此将 numpy.uint64 转换为带有 item 方法 decimal.Decimal

decimal.Decimal doesn't understand NumPy inputs, so convert the numpy.uint64 to a Python scalar with the item method before calling decimal.Decimal:

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

这篇关于Python Decimal模块在uint64上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆