mean ans std dev of an array?
Tim Chase
python.list at tim.thechases.com
Tue Oct 24 00:15:01 CEST 2006
> import array
> a = array.array('f', [1,2,3])
> print a.mean()
> print a.std_dev()
>
> Is there a way to calculate the mean and standard deviation on array
> data?
>
> Do I need to import it into a Numeric Array to do this?
No, you don't have to...though there are likely some stats
modules floating around. However, they're pretty simple to
implement:
>>> import array
>>> import math
>>> a = array.array('f', [1,2,3])
>>> mean = lambda a: sum(a)/len(a)
>>> mean(a)
2.0
>>> a
array('f', [1.0, 2.0, 3.0])
>>> def stdev(a):
... m = mean(a)
... return math.sqrt(sum((x-m) ** 2 for x in a) / len(a))
...
>>> stdev(a)
0.81649658092772603
Pretty much a no-brainer implementation of the algorithm
described at http://en.wikipedia.org/wiki/Standard_deviation
-tkc
More information about the Python-list
mailing list