Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Decimal module doesn't work on uint64

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
like image 204
Kyle Piira Avatar asked Oct 17 '25 22:10

Kyle Piira


1 Answers

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())
like image 124
user2357112 supports Monica Avatar answered Oct 20 '25 12:10

user2357112 supports Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!