我有这种方法:
这是一个求解器步进器,我决定使用生成器来开发它,以解决代码的优美性问题。这里的问题是u
的类型为:np.array
def step(f, t, u, dt):
def f(ti,ui):
return np.array([function(ti,ui) for function in func])
um3 = u
yield u + dt * f(t, u)
um2 = u
yield u + dt * f(t, u)
um1 = u
yield u + dt * f(t, u)
while True:
k1 = 55.0 * f(t, u)
k2 = 59.0 * f(t - dt, um1)
k3 = 37.0 * f(t - 2 * dt, um2)
k4 = 9.0 * f(t - 2 * dt, um3)
yield u + dt * (k1 - k2 + k3 - k4) / 24.0
um3 = um2
um2 = um1
um1 = u
编译时,标题中报告了错误。 我该如何解决?有可能有一个生成器返回一个数组吗?
编辑,谢谢您的关注!这里是完整的追溯:
Traceback (most recent call last):
File "drive.py", line 377, in <module>
main()
File "drive.py", line 224, in main
f.write('%f %f \n' %(t, u[0] )) # u[0]) )
TypeError: 'generator' object is not subscriptable
------------------------------------------------------------
@ friederikk99我调用生成器的代码是:
with open('AdamsBashforth4_p1.dat', 'w') as f:
while True:
f.write('%f %f \n' %(t, u[0] )) # u[0]) )
u = adamsmethods.AdamsBashforth._4th.step(func0,t,u,dt)
t += dt
if t > tf:
break
好,我已经更改了:
f.write('%f %f \n' %(t, np.array(u)[0]))
但是我收到了一条奇怪的消息:
Traceback (most recent call last):
File "drive.py", line 378, in <module>
main()
File "drive.py", line 225, in main
f.write('%f %f \n' %(t, np.array(u)[0])) # u[0]) )
IndexError: too many indices for array
我也尝试过这样:
f.write('%f %f \n' %(t, list(u)[0]))
...同样的错误