gpt4 book ai didi

python - 尝试为数据绘制拟合余弦平方函数,但无法正确绘制

转载 作者:太空宇宙 更新时间:2023-11-04 01:44:49 25 4
gpt4 key购买 nike

我已经按照我在网上找到的几个例子进行操作,但我仍然没有得到平滑的拟合曲线,我也不确定为什么。曲线应该主要跟随数据点,但是频率要高得多而且似乎不起作用,我不确定为什么。不知道还能说什么,我只是有点迷路..

import scipy as sp
import matplotlib.pyplot as plt
from scipy import linalg, optimize

X=sp.array([0.0,15.0,30.0,45.0,60.0,75.0,90.0,105.0,120.0,135.0,150.0,165.0,180.0,195.0,210.0,225.0,240.0,255.0,270.0,285.0,300.0,315.0,330.0,345.0,360.0])
Y=sp.array([196.3,282.0,337.0,347.0,312.0,240.0,152.0,69.0,15.3,1.1,33.0,105.4,195.4,195.4,286.0,345.0,362.0,256.0,162.0,75.0,14.9,1.3,35.1,105.2,194.9])

#DEBUG-------------------
print("Y len: ",len(Y))
print("X len: ",len(X))
#------------------------

def fit_func(x,a,c):
cosinesquare = a*sp.cos(x+c)**2
return cosinesquare

po, po_cov = sp.optimize.curve_fit(fit_func, X, Y, p0=[50,360])

#DEBUG------------------
print("po:",po)
print("po[0]: ",po[0])
print("po[1]: ",po[1])
#-----------------------

plt.scatter(X, Y, marker="x", label="Data")
plt.plot(X,fit_func(X, *po), label="Fitted func")
plt.xlabel("Angle of transmission axis")
plt.ylabel("voltage (mV)")
plt.grid()
plt.legend()
plt.show()

,

最佳答案

另一个答案有效,但真正的问题是您需要将度数转换为弧度。您可以添加 sp.pi/180 以在您的函数中进行转换。

import scipy as sp
import matplotlib.pyplot as plt
from scipy import linalg, optimize

X=sp.array([0.0,15.0,30.0,45.0,60.0,75.0,90.0,105.0,120.0,135.0,150.0,165.0,180.0,195.0,210.0,225.0,240.0,255.0,270.0,285.0,300.0,315.0,330.0,345.0,360.0])
Y=sp.array([196.3,282.0,337.0,347.0,312.0,240.0,152.0,69.0,15.3,1.1,33.0,105.4,195.4,195.4,286.0,345.0,362.0,256.0,162.0,75.0,14.9,1.3,35.1,105.2,194.9])

#DEBUG-------------------
print("Y len: ",len(Y))
print("X len: ",len(X))
#------------------------

def fit_func(x,a,c):
cosinesquare = a*sp.cos((x+c)*sp.pi/180.)**2
return cosinesquare

po, po_cov = sp.optimize.curve_fit(fit_func, X, Y, p0=[50,360])

#DEBUG------------------
print("po:",po)
print("po[0]: ",po[0])
print("po[1]: ",po[1])
#-----------------------

plt.scatter(X, Y, marker="x", label="Data")
plt.plot(X,fit_func(X, *po), label="Fitted func")
plt.xlabel("Angle of transmission axis")
plt.ylabel("voltage (mV)")
plt.grid()
plt.legend()
plt.show()

enter image description here

关于python - 尝试为数据绘制拟合余弦平方函数,但无法正确绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59297967/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com