Python - Math

From Torben's Wiki
Revision as of 22:18, 26 January 2024 by Torben (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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

Curve Fitting

from [1]

import numpy as np

# curve-fit() function imported from scipy
from scipy.optimize import curve_fit
from matplotlib import pyplot as plt

# Test function with coefficients as parameters
def fit_function(x, a, b):
    return a * np.exp(b * x)

p0 = [data_y[-1], 0.14]  # initial guess of parameters
param, param_cov = curve_fit(
    fit_function, data_x, data_y, p0, bounds=((-np.inf, -np.inf), (np.inf, np.inf))
)

print(f"Coefficients:\n{param}")
print(f"Covariance of coefficients:\n{param_cov}")

data_y_fit = []
for x in data_x:
    y = fit_function(x, param[0], param[1])
    data_y_fit.append(y)