mean ans std dev of an array?

Frederic Rentsch anthra.norell at vtxmail.ch
Wed Oct 25 07:28:36 EDT 2006


SpreadTooThin wrote:
> 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?
>
>   
I quickly fish this out of my functions toolbox. There's got to be 
faster functions in scipy, though.

Frederic

(Disclaimer: If you build an air liner or a ocean liner with this and 
the wings fall off at thirty thousand feet or it turns upside down in 
the middle of an ocean, respectively of course, I expect a bunch of 
contingency lawers lining up at my door wanting to sue you on my behalf.)


def standard_deviation (values):

   """
      Takes a sequence and returns mean, variance and standard deviation.
      Non-values (None) are skipped

   """

   import math
 
   mean = _sum_values_squared = _sum_values = 0.0

   l = len (values)
   i = 0
   item_count = 0
   while i < l:
      value = values [i]
      if value != None:
         _sum_values += value
         _sum_values_squared += value * value
         item_count += 1
      i += 1

   if item_count < 2:  # having skipped all Nones
      return None, None, None

   mean = _sum_values / item_count

   variance = (_sum_values_squared - item_count * mean * mean) / 
(item_count - 1)

   if variance < 0.0: variance = 0.0 
   # Rounding errors can cause minute negative values which would crash 
the sqrt

   standard_deviation = math.sqrt (variance)

   return mean, variance, standard_deviation





More information about the Python-list mailing list