曲线拟合正弦的 python 次方

curve fitting sine to the power of python

我想将信号拟合到余弦或正弦函数中:

参考信号:

sample_rate =1000
start_time = 0
end_time = 12

t = np.arange(start_time, end_time, 1/sample_rate)
amplitude = 12 #peak to peak
period = 60/15
n= 4

func =-amplitude* np.cos( np.pi *  t/period)**(2*n) +  amplitude

并且此信号必须适合模型:

def fit(t, a, b, n):
    return -a * np.cos(np.pi* t/(b))**(2*int(n)) + a 

通过做:

params, pcov = scipy.optimize.curve_fit(fit, t, func, )
a, b, n = params

我得到:

参数a = 11.9; b = 0.97 和 n=1

这根本不匹配...

将这些建议放在一起得出以下结果:

def fit(t, a, b, n):
    return -a * np.abs(np.cos(np.pi * t / b))**(2*n) + a 

params, pcov = scipy.optimize.curve_fit(
    fit, t, func, bounds=(0, np.inf), p0=(1, 3.5, 1))

print(*params)

plt.plot(t, func)
plt.plot(t, fit(t, *params), '--');

恢复你的参数。 bounds 加强了积极性,而 p0 给出了一个合理的起点建议,但拟合对这个选择非常敏感。