在python中拟合变量Sinc函数 [英] Fitting a variable Sinc function in python
问题描述
我想将sinc函数适合一堆数据线。
使用高斯拟合本身确实可以工作,但数据似乎不够高斯,因此我认为我可以切换到正弦。
I would like to fit a sinc function to a bunch of datalines. Using a gauss the fit itself does work but the data does not seem to be sufficiently gaussian, so I figured I could just switch to sinc..
I只是试图将一小段自运行的代码放在一起,但意识到,我可能不太了解,如果将数组移交给函数将如何处理数组,这可能是原因之一,为什么我会收到调用程序的错误消息
I just tried to put together a short piece of self running code but realized, that I probably do not fully understand, how arrays are handled if handed over to a function, which could be part of the reason, why I get error messages calling my program
所以我的代码当前如下所示:
So my code currently looks as follows:
from numpy import exp
from scipy.optimize import curve_fit
from math import sin, pi
def gauss(x,*p):
print(p)
A, mu, sigma = p
return A*exp(-1*(x[:]-mu)*(x[:]-mu)/sigma/sigma)
def sincSquare_mod(x,*p):
A, mu, sigma = p
return A * (sin(pi*(x[:]-mu)*sigma) / (pi*(x[:]-mu)*sigma))**2
p0 = [1., 30., 5.]
xpos = range(100)
fitdata = gauss(xpos,p0)
p1, var_matrix = curve_fit(sincSquare_mod, xpos, fitdata, p0)
我得到的是:
Traceback (most recent call last):
File "orthogonal_fit_test.py", line 18, in <module>
fitdata = gauss(xpos,p0)
File "orthogonal_fit_test.py", line 7, in gauss
A, mu, sigma = p
ValueError: need more than 1 value to unpack
据我了解,p没有正确交出,这很奇怪,因为它在我手中实际代码。安装后,我会从sincSquare函数获得类似的消息,可能是同一类型的错误。我对这家星级经营者还算陌生,所以可能隐藏了一个小故障...
From my understanding p is not handed over correctly, which is odd, because it is in my actual code. I then get a similar message from the sincSquare function, when fitted, which could probably be the same type of error. I am fairly new to the star operator, so there might be a glitch hidden...
有人有什么想法吗? :)
Anybody some ideas? :)
谢谢!
推荐答案
您需要进行三处更改,
def gauss(x, A, mu, sigma):
return A*exp(-1*(x[:]-mu)*(x[:]-mu)/sigma/sigma)
def sincSquare_mod(x, A, mu, sigma):
x=np.array(x)
return A * (np.sin(pi*(x[:]-mu)*sigma) / (pi*(x[:]-mu)*sigma))**2
fitdata = gauss(xpos,*p0)
1,请参见文档
2,将 sin
替换为 array的
numpy
版本 code>广播
2, replace sin
by the numpy
version for array
broadcasting
3,直截了当吧? :P
3, straight forward right? :P
注意,我想您正在寻找的是 p1,var_matrix = curve_fit(gauss,...
而不是比OP中的那个没有解决方案。
Note, i think you are looking for p1, var_matrix = curve_fit(gauss,...
rather than the one in the OP, which appears do not have a solution.
这篇关于在python中拟合变量Sinc函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!