【问题标题】:How to Implement 'if' Statement for a Function to Solve a System of ODEs using solve_ivp in PythonHow to Implement \'if\' Statement for a Function to Solve a System of ODEs using solve_ivp in Python
【发布时间】:2022-12-02 10:50:28
【问题描述】:

For the time, t, from 0 to 30, z0 is a constant value of 6. For the time,t, from 30 to 100, z0 takes on the form of a time variable where z0 = 6exp(-0.5*(t-15)). I tried to implement the 'if' condition in my function but it does not seem to work. Is there anything I am doing wrong? Any help will be appreciated.

z0 = 6
z0_new = z0*np.exp(-0.5*(t-15))
def f(t,y):
    return z0-y[0],3/y[0]-y[1]
fsol = solve_ivp(f,(0,100),[3,350])
plt.plot(fsol.t,fsol.y[0])

z0 = 6
def f(t,y):
    if t>=30: 
        z0 = 6*np.exp(-0.5*(t-15))
    return z0-y[0],3/y[0]-y[1]
fsol = solve_ivp(f,(0,100),[3,350])
plt.plot(fsol.t,fsol.y[0])

【问题讨论】:

  • I recommend finding a way to solve this problem without a global variable. You should implement the function f() directly from the piecewise definition of your function. For example, nothing in your f() function says anything about the interval from 0 to 30.

标签: python if-statement math ode


【解决方案1】:

You just put an elif block after your initial if condition. You don't make 2 functions.

def f(t,y):
    if 0 <= t <= 30:
        z0 = 6
    elif t > 30: 
        z0 = 6 * np.exp(-0.5 * (t - 15))
    else:
        return f"t value {t} is less than zero"
    return z0 - y[0], 3 / y[0] - y[1]

fsol = solve_ivp(f, (0,100), [3,350])
plt.plot(fsol.t, fsol.y[0])

【讨论】:

    猜你喜欢
    • 2022-12-26
    • 2022-12-01
    • 2022-12-02
    • 2022-11-20
    • 1970-01-01
    • 2022-12-27
    • 2022-12-02
    • 2022-12-01
    • 2022-12-27
    相关资源
    最近更新 更多