我正在创建一个类,以便对不同的问题执行多项操作(例如求解,绘图,将解决方案保存到文件中) 步进器是更重要的部分,我想将我的代码从简单的类方法修改为生成器
以下是我可用的代码的简短提示:
import numpy as np
first_startup , second_startup, third_startup = True, True, True
um1,um2,um3 = 0.,0.,0.
def step(f , t : np.float , u : np.float , dt):
global first_startup , second_startup, third_startup
global um1,um2,um3
if first_startup:
um3 = u.copy()
unext = u + dt*f(t,u) #rungekutta.RK4.step(func,t,um2,dt)
t += dt
first_startup = False
elif second_startup:
um2 = u.copy()
unext = unext = u + dt*f(t,u) #rungekutta.RK4.step(func,t,um2,dt)
t+= dt
second_startup = False
elif third_startup:
um1 = u.copy()
unext = u + dt*f(t,u) #rungekutta.RK4.step(func,t,um1,dt)
t += dt
third_step = False
else: # compute AB 4th order
unext = u + dt/24.* ( 55.*f(t,u) - 59.*f(t-dt,um1) + 37.*f(t-dt-dt,um2) \
- 9.*f(t-dt-dt,um3 ))
um3 = um2.copy()
um2 = um1.copy()
um1 = u.copy()
return unext
def main():
func = lambda t,u : -10*(t-1)*u
t0 = 0.
tf = 2.
dt = 2/50
u = np.exp(-5)
t = t0
with open('output.dat', 'w') as f:
while True:
f.write('%f %f \n' %(t, u) )
u = step(func,t,u,dt)
t += dt
if t > tf:
break
if __name__ == '__main__':
main()
有可能创建一个生成器,以便在步进器的3个调用中返回if,elif,else块内的值计算(这里我写了一个简单的方法,但是在步进器中我将调用注释了)是个好主意,我该怎么办?
EDIT jdowner我已注释掉了对runge-kutta的调用,因为我只想提供一个最小的工作代码,即对runge-kutta的调用已完成,以启动多步操作(因此,请输入4step)需要计算3点才能启动该方法)
编辑 Ilia L,但在运行多步方法的过程中我也需要使用这3个变量。
编辑 我收到此错误:
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) ) # u[0]) )
TypeError: must be real number, not generator
答案 0 :(得分:1)
如果要使用生成器执行上述计算,我会这样写,
def step(f, t, u, dt):
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