User Tools

Site Tools


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))
    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(, A),, 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