python函数拟合不规则曲线_如何在Python中进行指数和对数曲线拟合?我发现只有多项式拟合...

我在这方面遇到了一些麻烦所以让我非常明确,所以像我这样的新手可以理解。

让我们说我们有一个数据文件或类似的东西# -*- coding: utf-8 -*-import matplotlib.pyplot as pltfrom scipy.optimize import curve_fitimport numpy as npimport sympy as sym"""

Generate some data, let's imagine that you already have this.

"""x = np.linspace(0, 3, 50)y = np.exp(x)"""

Plot your data

"""plt.plot(x, y, 'ro',label="Original Data")"""

brutal force to avoid errors

""" x = np.array(x, dtype=float) #transform your data in a numpy array of floats y = np.array(y, dtype=float) #so the curve_fit can work"""

create a function to fit with your data. a, b, c and d are the coefficients

that curve_fit will calculate for you.

In this part you need to guess and/or use mathematical knowledge to find

a function that resembles your data

"""def func(x, a, b, c, d):

return a*x**3 + b*x**2 +c*x + d"""

make the curve_fit

"""popt, pcov = curve_fit(func, x, y)"""

The result is:

popt[0] = a , popt[1] = b, popt[2] = c and popt[3] = d of the function,

so f(x) = popt[0]*x**3 + popt[1]*x**2 + popt[2]*x + popt[3].

"""print "a = %s , b = %s, c = %s, d = %s" % (popt[0], popt[1], popt[2], popt[3])"""

Use sympy to generate the latex sintax of the function

"""xs = sym.Symbol('\lambda') tex = sym.latex(func(xs,*popt)).replace('$', '')plt.title(r'$f(\lambda)= %s$' %(tex),fontsize=16)"""

Print the coefficients and plot the funcion.

"""plt.plot(x, func(x, *popt), label="Fitted Curve") #same as line above \/#plt.plot(x, popt[0]*x**3 + popt[1]*x**2 + popt[2]*x + popt[3], label="Fitted Curve") plt.legend(loc='upper left')plt.show()

结果是:a = 0.849195983017,b = -1.18101681765,c = 2.24061176543,d = 0.816643894816

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值