出现此错误,ValueError:使用序列设置数组元素。我在没有oop的情况下做到了,而且做得很好。我需要def loop(self)的数据:将其传递给def f(self,x,y):并保持同步
class rungekuta():
def __init__(self):
self.x = np.linspace(1, 5, 50)
self.y = np.zeros(len(self.x))
self.y[0] = 4
self.loop()
self.f()
def f(self, x, y):
return (self.x*np.sqrt(self.y))
def loop(self):
h = 0.2
for i in range(len(self.x) - 1):
k1 = self.f(self.x[i], self.y[i])
k2 = self.f(self.x[i] + h / 2, self.y[i] + k1 * (h / 2))
k3 = self.f(self.x[i] + h / 2, self.y[i] + k2 * (h / 2))
k4 = self.f(self.x[i] + h, self.y[i] + k3 * h)
self.y[i+1] = self.y[i]+(h / 6) * (k1 + 2 * k2 + 2 * k3 + k4)
def draw(self):
plt.plot(self.x, self.y)
plt.show()
run = rungekuta()
run.draw()
这是没有opp python的算法
def f(x,y):
return (x*np.sqrt(y))
def rk4(f,a,b,y0,h):
x=np.arange(a,b,h)
n=len(x)
k1=np.zeros(len(x))
k2=np.zeros(len(x))
k3=np.zeros(len(x))
k4=np.zeros(len(x))
y=np.zeros(len(x))
y[0]=y0
for i in range(0,len(x)-1):
k1[i]=f(x[i],y[i])
k2[i]=f(x[i]+h/2,y[i]+k1[i]*(h/2))
k3[i]=f(x[i]+h/2,y[i]+k2[i]*(h/2))
k4[i]=f(x[i]+h,y[i]+k3[i]*h)
y[i+1]=y[i]+(h/6)*(k1[i]+2*k2[i]+2*k3[i]+k4[i])
plt.plot(x,y)
plt.show()
rk4(f,1,5,4,0.2)
所有的问题都是类中的方法
f()
。它获取x
,y
,并且应该使用x
,y
,而不是self.x
,self.y
您应该从
__init__
中删除self.f()
PEP 8 - Style Guide for Python Code
相关问题 更多 >
编程相关推荐