数值求解微分方程

Solving differential equations numerically

我尝试用数值方法求解一个非常简单的方程 f = t**2。我编写了一个for循环,以便在第一个时间步使用f,然后将每个循环的解决方案用作下一个循环的初始函数。

我不确定我用数字求解它的方法是否正确,并且出于某种原因我的循环只工作两次(一次通过 if- 然后是 else 语句)然后只给出零。

非常感谢任何帮助。谢谢!!!

## IMPORT PACKAGES
import numpy as np
import math
import sympy as sym
import matplotlib.pyplot as plt

## Loop to solve numerically

for i in range(1,4,1):
    if i == 1:
        f_old = t**2
        print(f_old)
    else: 
        f_old = sym.diff(f_old, t).evalf(subs={t: i})
        f_new = f_old + dt * (-0.5 * f_old)
        f_old = f_new
        print(f_old)

Scipy.integrate 包中有一个名为 odeint 的函数,用于求解微分方程

这是一些资源 Link 1 Link 2

y = odeint(model, y0, t)

model:returns 请求的 y 和 t 值的导数作为 dydt = model(y,t)

的函数名称

y0:微分状态的初始条件

t:应报告解决方案的时间点。通常会计算额外的内部点以保持解决方案的准确性,但不会报告。

同样绘制结果的示例:

import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt

# function that returns dy/dt
def model(y,t):
    k = 0.3
    dydt = -k * y
    return dydt

# initial condition
y0 = 5

# time points
t = np.linspace(0,20)

# solve ODE
y = odeint(model,y0,t)

# plot results
plt.plot(t,y)
plt.xlabel('time')
plt.ylabel('y(t)')
plt.show()