【问题标题】:Numpy with Python's Decimal argumentsNumpy 与 Python 的 Decimal 参数
【发布时间】:2014-04-23 19:55:39
【问题描述】:

我有一个小问题。 在我的程序中,在 Python 3.3 中,我列出了十进制值 (x):

  [Decimal('646'), Decimal('651'), Decimal('657')]

我想知道使用 Numpy 的平均值。

所以我写了:

  tempArray = numpy.array(x, dtype=np.dtype(decimal.Decimal))

但我得到了错误:

  TypeError: unsupported operand type(s) for /: 'decimal.Decimal' and 'float'

我的代码有什么问题?

【问题讨论】:

  • 你用的是什么版本的 Python?
  • 您使用小数而不是浮点数有什么特殊原因吗?
  • 你写了“我想知道平均值”,但是你有tempArray = numpy.array(...) - 并且numpy.mean在这个OP的任何地方都没有使用?

标签: python numpy decimal


【解决方案1】:

以下内容在 Python 2.7 上对我来说很好

import numpy
from decimal import Decimal

x = [Decimal('646'), Decimal('651'), Decimal('657')]
tempArray = numpy.array(x, dtype=numpy.dtype(Decimal))
print numpy.mean(tempArray)

【讨论】:

  • 嗯,马特,这段代码不能在我的 Python 3.3 中运行。我在上面提到过同样的错误:TypeError: unsupported operand type(s) for /: 'decimal.Decimal' and 'float'
  • 如果你只是去掉 dtype=numpy.dtype(Decimal) 并做 tempArray = numpy.array(x)
  • 现在出现同样的错误。与您的代码相比,我的代码中唯一的变化是 print 函数,它有括号:print (numpy.mean(tempArray)),因为 Python 3 标准。而现在,当我摆脱 dtype=numpy.dtype(Decimal) 问题时也是一样的。
  • 看起来 numpy 没有 Decimal 的概念,只是使它成为一个通用对象。如果您执行 numpy.array(x, dtype=float) 它应该可以工作
【解决方案2】:

为什么需要使用 Numpy?这可以很容易地完成

>>> sum(x)/len(x)
Decimal('651.3333333333333333333333333')

也就是说,我能做到

>>> np.array(x).mean()
Decimal('651.3333333333333333333333333')

【讨论】:

    猜你喜欢
    • 2011-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-11
    相关资源
    最近更新 更多