User Tools

Site Tools


num-ansys:start

Numerical Analysis

Polynomial curve fitting

import numpy as np
 
def polyfit(x, fx, w, n):
    """Calculate the coeffients of the polynomial that best approximate (x, y).
 
    :param x (list): indipendent variable
    :param fx (list): dipendent variable
    :param w (list): weight of each node
    :param n (int): degree of the polynomial
    :return a (list): coeffientes of the polynomial
    """
    A = []
    for i in range(len(x)):  # rows
        r = []
        for j in range(n, 0, -1):  # columns
            r.append(w[i]**.5 * x[i]**(n-j))
        A.append(r)
 
    b = []
    for i in range(len(x)):  # columns
        b.append([w[i]**.5 * fx[i]])
 
    A = np.array(A)
    b = np.array(b)
 
    a = np.linalg.lstsq(np.dot(A.T, A), np.dot(A.T, b))  # (A' * A) \ (A' * b)
    a = a[0].T.tolist()[0]
 
    return a
num-ansys/start.txt · Last modified: 2020/05/24 08:45 by tormec