Standard Deviation One-liner

Raymond Hettinger python at rcn.com
Fri Jun 3 16:09:43 EDT 2011


On Jun 3, 10:55 am, Billy Mays <no... at nohow.com> wrote:
> I'm trying to shorten a one-liner I have for calculating the standard
> deviation of a list of numbers.  I have something so far, but I was
> wondering if it could be made any shorter (without imports).
>
> Here's my function:
>
> a=lambda d:(sum((x-1.*sum(d)/len(d))**2 for x in d)/(1.*(len(d)-1)))**.5
>
> The functions is invoked as follows:
>
>  >>> a([1,2,3,4])
> 1.2909944487358056

Besides trying to do it one line, it is also interesting to write an
one-pass version with incremental results:

  http://mathcentral.uregina.ca/QQ/database/QQ.09.06/h/murtaza2.html

Another interesting avenue to is aim for highest possible accuracy.
Consider using math.fsum() to avoid rounding errors in the summation
of large numbers of nearly equal values.


Raymond

-------------
follow my python tips on twitter: @raymondh





More information about the Python-list mailing list