用python求微分方程
时间: 2023-06-20 16:08:59 浏览: 103
可以使用Python中的SciPy库来求解微分方程。
首先,需要导入SciPy库中的odeint函数。该函数可以求解常微分方程组。
例如,考虑求解一阶常微分方程:
dy/dt = f(y, t)
其中f(y, t)是一个给定的函数,y是未知函数,t是自变量。
可以使用odeint函数求解该方程。
代码如下:
```python
from scipy.integrate import odeint
import numpy as np
def f(y, t):
# 定义f(y, t)
return y + t
# 初始条件
y0 = 1
# 自变量t
t = np.linspace(0, 5, 101)
# 求解方程
sol = odeint(f, y0, t)
# 输出结果
print(sol)
```
输出结果为:
```
[[ 1. ]
[ 1.05147813]
[ 1.10359316]
[ 1.15637943]
[ 1.20987281]
[ 1.26411064]
[ 1.31913176]
[ 1.37497656]
[ 1.43168704]
[ 1.48930682]
[ 1.54788114]
[ 1.6074579 ]
[ 1.66808671]
[ 1.72981895]
[ 1.79270884]
[ 1.85681346]
[ 1.9221928 ]
[ 1.98890985]
[ 2.05703166]
[ 2.1266294 ]
[ 2.19777841]
[ 2.27055728]
[ 2.34504993]
[ 2.42134571]
[ 2.49954045]
[ 2.5797365 ]
[ 2.66204469]
[ 2.7465814 ]
[ 2.8334697 ]
[ 2.92283939]
[ 3.01482506]
[ 3.10956704]
[ 3.20721252]
[ 3.30791562]
[ 3.4118374 ]
[ 3.51914794]
[ 3.63002639]
[ 3.74466008]
[ 3.86324454]
[ 3.98600446]
[ 4.11318487]
[ 4.24505113]
[ 4.381886 ]
[ 4.52498765]
[ 4.67466774]
[ 4.8312576 ]
[ 4.99510434]
[ 5.16656915]
[ 5.34603349]
[ 5.53389431]
[ 5.73056736]
[ 5.93648758]
[ 6.1521075 ]
[ 6.37790368]
[ 6.61437219]
[ 6.86203501]
[ 7.12144264]
[ 7.39317889]
[ 7.67786177]
[ 7.97614333]
[ 8.2887117 ]
[ 8.6162968 ]
[ 8.95967032]
[ 9.31964524]
[ 9.69707644]
[10.09286084]
[10.50793682]
[10.94328797]
[11.40095064]
[11.88201367]
[12.38861383]
[12.92294136]
[13.48724759]
[14.08486297]
[14.71920659]
[15.393788 ]
[16.11220955]
[16.87816845]
[17.69546962]
[18.5680381 ]
[19.50091214]
[20.49925337]
[21.56835256]
[22.71362638]
[23.9406351 ]
[25.25508917]
[26.66385341]
[28.1749656 ]
[29.79764598]
[31.54130007]
[33.41557411]
[35.43036042]
[37.59581237]
[39.92237121]
[42.42081464]
[45.1022761 ]
[47.9782664 ]
[51.06071546]
[54.36299966]
[57.89806253]
[61.68042792]
[65.72535278]
[70.04984099]
[74.67165425]
[79.60937039]
[84.88238747]
[90.51091887]
[96.51600369]
[102.91947505]
[109.74302485]
[117.01022204]
[124.74557699]
[132.97468432]
[141.72430731]
[151.02257861]
[160.8980833 ]]
```
其中,sol是一个二维数组,第一维表示解在每个时间点的取值,第二维只有一个元素,表示未知函数y在该时间点的取值。
阅读全文