0

我做了一些工作,最后我得到了一个数据,它的形状看起来像 sinc 函数,我试图搜索如何使用 numpy 将图形拟合到 sinc 函数,我发现了这个:

在 python 中拟合变量 Sinc 函数

我找到它很好,但我想为什么它看起来很复杂?

你能给我更友好的方式来拟合给我像 sinc 函数这样的曲线的图形吗?

4

1 回答 1

2

很好地执行拟合您提供的链接中提供的答案就足够了。但是,既然你说你觉得很难,我有一个示例代码,其中包含正弦曲线形式的数据和一个适合数据的用户定义函数。

这是代码:

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import math

xdata = np.array([2.65, 2.80, 2.96, 3.80, 3.90, 4.60, 4.80, 4.90, 5.65, 5.92])
ydata = np.sin(xdata)

def func(x,p1,p2,p3): # HERE WE DEFINE A SIN FUNCTION THAT WE THINK WILL FOLLOW THE DATA DISTRIBUTION
    return p1*np.sin(x*p2+p3)

# Here you give the initial parameters for p0 which Python then iterates over
# to find the best fit
popt, pcov = curve_fit(func,xdata,ydata,p0=(1.0,1.0,1.0)) #THESE PARAMETERS ARE USER DEFINED

print(popt) # This contains your two best fit parameters

# Performing sum of squares
p1 = popt[0]
p2 = popt[1]
p3 = popt[2]
residuals = ydata - func(xdata,p1,p2,p3)
fres = sum(residuals**2)

print(fres) #THIS IS YOUR CHI-SQUARE VALUE!

xaxis = np.linspace(1,7,100) # we can plot with xdata, but fit will not look good 
curve_y = func(xaxis,p1,p2,p3)
plt.plot(xdata,ydata,'*')
plt.plot(xaxis,curve_y,'-')
plt.show()

在此处输入图像描述

你也可以访问这个网站!!并逐步了解 curve_fit 的工作原理。

于 2014-06-20T19:08:39.317 回答