python多項式擬合:np.polyfit 和 np.polyld


python數據擬合主要可采用numpy庫,庫的安裝可直接用pip install numpy等。

1. 原始數據:假如要擬合的數據yyy來自sin函數,np.sin

import numpy as np
import matplotlib.pyplot as plt
xxx
= np.arange(0, 1000) # x值,此時表示弧度 yyy = np.sin(xxx*np.pi/180) #函數值,轉化成度

2. 測試不同階的多項式,例如7階多項式擬合,使用np.polyfit擬合,np.polyld得到多項式系數

z1 = np.polyfit(xxx, yyy, 7) # 用7次多項式擬合,可改變多項式階數;
p1 = np.poly1d(z1) #得到多項式系數,按照階數從高到低排列
print(p1)  #顯示多項式

 3. 求對應xxx的各項擬合函數值

yvals=p1(xxx) # 可直接使用yvals=np.polyval(z1,xxx)

4. 繪圖如下

plt.plot(xxx, yyy, '*',label='original values')
plt.plot(xxx, yvals, 'r',label='polyfit values')
plt.xlabel('x axis')
plt.ylabel('y axis')
plt.legend(loc=4) # 指定legend在圖中的位置,類似象限的位置
plt.title('polyfitting')
plt.show()

 5. np.polyfit函數:采用的是最小二次擬合,numpy.polyfit(xydegrcond=Nonefull=Falsew=Nonecov=False),前三個參數是必須的

官方文檔:https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.polyfit.html

6. np.polyld函數:得到多項式系數,主要有三個參數

    A one-dimensional polynomial class.

    A convenience class, used to encapsulate "natural" operations on
    polynomials so that said operations may take on their customary
    form in code (see Examples).

    Parameters
    ----------
    c_or_r : array_like
        The polynomial's coefficients, in decreasing powers, or if
        the value of the second parameter is True, the polynomial's
        roots (values where the polynomial evaluates to 0).  For example,
        ``poly1d([1, 2, 3])`` returns an object that represents
        :math:`x^2 + 2x + 3`, whereas ``poly1d([1, 2, 3], True)`` returns
        one that represents :math:`(x-1)(x-2)(x-3) = x^3 - 6x^2 + 11x -6`.
    r : bool, optional
        If True, `c_or_r` specifies the polynomial's roots; the default
        is False.
    variable : str, optional
        Changes the variable used when printing `p` from `x` to `variable`
        (see Examples).

參數1表示:在沒有參數2(也就是參數2默認False時),參數1是一個數組形式,且表示從高到低的多項式系數項,例如參數1為[4,5,6]表示:

 參數2表示:為True時,表示將參數1中的參數作為根來形成多項式,即參數1為[4,5,6]時表示:(x-4)(x-5)(x-6)=0,也就是:

 參數3表示:換參數標識,用慣了x,可以用 t,s之類的

 

用法:

1. 直接進行運算,例如多項式的平方,分別得到

xx=np.poly1d([1,2,3])
print(xx)
yy=xx**2  #求平方,或者用 xx * xx
print(yy)

 

 2. 求值:

yy(1) = 36

3. 求根:即等式為0時的未知數值

yy.r

4. 得到系數形成數組:

yy.c 為:array([ 1,  4, 10, 12,  9])

5. 返回最高次冪數:

yy.order = 4

6. 返回系數:

yy[0] —— 表示冪為0的系數

yy[1] —— 表示冪為1的系數

 

參考:

https://www.cnblogs.com/zhouzhe-blog/p/9621679.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM