【发布时间】:2022-12-01 06:56:44
【问题描述】:
您好我正在编写一个程序,该程序旨在为分配的不同 ODE 执行 RK4 方法。我们必须使用的东西之一是 *args。当我调用包含 *args(rk4 一个)的函数时,我在最后列出了额外的参数。当我尝试运行它时,它说我的函数(在本例中为 f2a)缺少 3 个必需的位置参数,即使我已将它们包含在我认为是 RK4 函数参数列表的 args 部分的末尾。这是否意味着我没有指出这些是正确的额外参数?或者我是否需要将它们添加到我正在使用 RK4 的功能中?我对编码真的很陌生,所以非常感谢任何帮助。这是我的整个代码:
import numpy as np
import math
import matplotlib.pyplot as plt
#defining functions
H0=7 #initial height, meters
def f2a(t,H,k,Vin,D):
dhdt=4/(math.pi*D**2)*(Vin-k*np.sqrt(H))
return(dhdt)
def fb2(J,t):
x=J[0]
y=J[1]
dxdt=0.25*y-x
dydt=3*x-y
#X0,Y0=1,1 initial conditions
return([dxdt,dydt])
#x0 and y0 are initial conditions
def odeRK4(function,tspan,R,h,*args):
#R is vector of inital conditions
x0=R[0]
y0=R[1]
#writing statement for what to do if h isnt given/other thing
if h==None:
h=.01*(tspan[1]-tspan[0])
elif h> tspan[1]-tspan[0]:
h=.01*(tspan[1]-tspan[0])
else:
h=h
#defining the 2-element array (i hope)
#pretty sure tspan is range of t values
x0=tspan[0] #probably 0 if this is meant for time
xn=tspan[1] #whatever time we want it to end at?
#xn is final x value-t
#x0 is initial
t_values=np.arange(x0,21,1) #0-20
N=len(t_values)
y_val=np.zeros(N)
y_val[0]=y0
#I am trying to print all the Y values into this array
for i in range(1,N):
#rk4 method
#k1
t1=t_values[i-1] #started range @ 1, n-1 starts at 0
y1=y_val[i-1]
k1=function(t1,y1)
#k2
t2=t_values[i-1]+0.5*h
y2=y_val[i-1]+0.5*k1*h
k2=function(t2,y2)
#k3
t3=t_values[i-1]+0.5*h
y3=y_val[i-1]+0.5*k2*h
k3=function(t3,y3)
#k4
t4=t_values[i-1]+h
y4=y_val[i-1]+h*k3
k4=function(t4,y4)
y_val[i]=y_val[i-1]+(1/6)*h*(k1+2*k2+2*k3+k4)
#this fills the t_val array and keeps the loop going
a=np.column_stack(t_values,y_val)
print('At time T, Y= (t on left,Y on right)')
print(a)
plt.plot(t_values,y_val)
print('For 3A:')
#k=10, told by professor bc not included in instructions
odeRK4(f2a, [0,20],[0,7], None, 10,150,7)
【问题讨论】:
-
是的,您需要将
*args从 RK4 传递给您正在集成的功能。否则它会如何工作?现在您只将两个参数传递给传递给 RK4 的function。
标签: python