Python - Math

From Torben's Wiki


Average of List

def myMean(L):
  return float(sum(L)) / len(L)

Lin Reg

from math import sqrt
def myLinReg(X, Y):
    """
        Linear regression of y = ax + b
        real a, real b = linreg(X, Y)
    """
    if len(X) != len(Y):  raise ValueError, 'unequal length'
    N = len(X)
    if   N == 0:
      raise ValueError, 'list too short'
      a = b = 0.0
    elif N == 1:
      a = 0
      b = Y[0]
    elif N == 2:
      a = float(X[0]-X[1])/(Y[0]-Y[1])
      b = Y[0]-a*X[0]
    else :
      Sx = Sy = Sxx = Syy = Sxy = 0.0 # sums
      for x, y in map(None, X, Y):
          Sx = Sx + x
          Sy = Sy + y
          Sxx = Sxx + x*x
          Syy = Syy + y*y
          Sxy = Sxy + x*y
      det = Sxx * N - Sx * Sx
      if det == 0.0 : det = 1e-5 # workaround
      a, b = (Sxy * N - Sy * Sx)/det, (Sxx * Sy - Sx * Sxy)/det
      #meanerror = residual = 0.0
      #for x, y in map(None, X, Y):
      #    meanerror = meanerror + (y - Sy/N)**2
      #    residual = residual + (y - a * x - b)**2
      #if meanerror == 0.0 : meanerror = 1e-5 # workaround
      #RR = 1 - residual/meanerror
      #ss = residual / (N-2)
      #Var_a, Var_b = ss * N / det, ss * Sxx / det
    return a, b