2

I am attempting to take the weighted average of a list of Decimal numbers using numpy.average; however, I am receiving a TypeError. For example, consider the following.

>>> from decimal import *
>>> import numpy
>>> s = '1.00000001'
>>> l = []
>>> l.append(Decimal(s))
>>> l.append(Decimal(s))
>>> numpy.average(l)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.6/site-packages/numpy/lib/function_base.py", line 612
, in average
    avg = a.mean(axis)
TypeError: unsupported operand type(s) for /: 'Decimal' and 'float'

How do I take the weighted average of a list of Decimal numbers without converting to a float and losing precision of the values using numpy?

idealistikz
  • 1,247
  • 5
  • 21
  • 35
  • 1
    Er, are you sure that you're asking for a [_weighted_ average](http://en.wikipedia.org/wiki/Weighted_mean)? If so, you need a weight for each corresponding value. It seems like you're trying to get an arithmetic average instead. – voithos Jun 11 '12 at 04:52
  • See also: [numpy array with dtype Decimal?](http://stackoverflow.com/a/7772386/222914) – Janne Karila Jun 11 '12 at 06:54
  • numpy is not the tool for you if you really need to work with Decimal values. – Phil Cooper Jun 11 '12 at 19:09

1 Answers1

2

Err, the classic way...

>>> sum((decimal.Decimal(1), decimal.Decimal(2))) / 2
Decimal('1.5')
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358