gpt4 book ai didi

Python Decimal 模块不适用于 uint64

转载 作者:行者123 更新时间:2023-12-04 02:06:13 25 4
gpt4 key购买 nike

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

>>> 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 输入,因此将 numpy.uint64 转换为带有 item method 的 Python 标量在调用 decimal.Decimal 之前:

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

关于Python Decimal 模块不适用于 uint64,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43214243/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com