python多项式拟合数据

python中对任意数据进行多项式拟合

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

'拟合过程中应当注意,坐标的顺序'

__author__ = 'alluring'

import numpy as np
import matplotlib.pyplot as plt
def fit(fit_x,fit_y,fit_num = 7):#fit_num表示自由度为7进行拟合数据
    fit_x = np.array(fit_x)
    fit_y = np.array(fit_y)
    f1 = np.polyfit(fit_x, fit_y, fit_num)
    p1 = np.poly1d(f1)#p1为生成的拟合多项式
    # yfit = p1(fit_x)
    print(p1)
    return p1

y = [0,0,0.2,0.5,1,1.5,2,2.5,3,3.5,4,4.3,4,3.5,2.5,2,1.5,1,0.5,0.2,0,0]
x = [0,1,2,2.75,3.2,3.7,4.15,4.5,5,5.4,6.2,7,8.5,9.3,10.3,11,11.7,12.8,13.5,15,16,17]
fit(x,y)
fitx = []
iu = 0
while iu <= 17:
    iu += 0.01
    fitx.append(iu)
plt.plot(x,y)
plt.plot(fitx,list(map(fit(x,y),fitx)),label = 'nihe')#map为python的内置函数,可以将函数分别作用于后面的数据中
plt.legend()
plt.show()

结果:

1557929806832
在这里插入图片描述

发布了22 篇原创文章 · 获赞 59 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/weixin_43245453/article/details/90246453