我编写了一个代码,该代码可以观察物体在拖动时的弹丸运动。我正在使用scipy中的odeint进行正向Euler方法。集成运行直到达到时间限制。我想在达到此限制或ry = 0(即弹丸着陆)的输出时停止积分。
def f(y, t):
# takes vector y(t) and time t and returns function y_dot = F(t,y) as a vector
# y(t) = [vx(t), vy(t), rx(t), ry(t)]
# magnitude of velocity calculated
v = np.sqrt(y[0] ** 2 + y[1] **2)
# define new drag constant k
k = cd * rho * v * A / (2 * m)
return [-k * y[0], -k * y[1] - g, y[0], y[1]]
def solve_f(v0, ang, h0, tstep, tmax=1000):
# uses the forward Euler time integration method to solve the ODE using f function
# create vector for time steps based on args
t = np.linspace(0, tmax, tmax / tstep)
# convert angle from degrees to radians
ang = ang * np.pi / 180
return odeint(f, [v0 * np.cos(ang), v0 * np.sin(ang), 0, h0], t)
solution = solve_f(v0, ang, h0, tstep)
我尝试了多个循环,并尝试在ry = 0时尝试停止积分。并在下面找到了此问题,但无法使用odeint实现类似的功能。 solution [:,3]是ry的输出列。有没有使用odeint做到这一点的简单方法?
答案 0 :(得分:0)
结帐scipy.integrate.ode
here。它比odeint
更加灵活,可以帮助您完成所需的工作。
一个使用垂直镜头的简单示例,该示例一直集成到地面:
from scipy.integrate import ode, odeint
import scipy.constants as SPC
def f(t, y):
return [y[1], -SPC.g]
v0 = 10
y0 = 0
r = ode(f)
r.set_initial_value([y0, v0], 0)
dt = 0.1
while r.successful() and r.y[0] >= 0:
print('time: {:.3f}, y: {:.3f}, vy: {:.3f}'.format(r.t + dt, *r.integrate(r.t + dt)))
每次调用r.integrate
时,r
将存储当前时间和y值。如果要存储它们,可以将它们传递到列表中。
答案 1 :(得分:0)
让我们以此解决边界问题。我们有条件x(0)=0, y(0)=h0, vx(0)=0, vy(0)=0
和y(T)=0
。要设置固定的积分间隔,请设置t=T*s
,这意味着dx/ds=T*dx/dt=T*vx
等。
def fall_ode(t,u,p):
vx, vy, rx, ry = u
T = p[0]
# magnitude of velocity calculated
v = np.hypot(vx, vy)
# define new drag constant k
k = cd * rho * v * A / (2 * m)
return np.array([-k * vx, -k * vy - g, vx, vy])*T
def solve_fall(v0, ang, h0):
# convert angle from degrees to radians
ang = ang * np.pi / 180
vx0, vy0 = v0*np.cos(ang), v0*np.sin(ang)
def fall_bc(y0, y1, p): return [ y0[0]-vx0, y0[1]-vy0, y0[2], y0[3]-h0, y1[3] ]
t_init = [0,1]
u_init = [[0,0],[0,0],[0,0], [h0,0]]
p_init = [1]
res = solve_bvp(fall_ode, fall_bc, t_init, u_init, p_init)
print res.message
if res.success:
print "time to ground: ", res.p[0]
# res.sol is a dense output, evaluation interpolates the computed values
return res.sol
sol = solve_fall(300, 30, 20)
s = np.linspace(0,1,501)
u = sol(s)
vx, vy, rx, ry = u
plt.plot(rx, ry)