赞
踩
因科研需要,我要求复数odes,首先想python scipy 能不能求,例如dx/dt=ix ,应该能求出振荡解。于是有了下面代码。
注意代码中只对y1进行了求解,初始条件一定要写成a+bj(或bj)的形式,告诉它你的初值是复数,即使虚部可能为零。如果只填个实数,后面求解会把dydt中取实部。然后算出来就是一条直线。
- import numpy as np
- from scipy.integrate import solve_ivp
- import matplotlib.pyplot as plt
-
- # 定义常微分方程组
- def equations(t, y):
- [y1] = y
- dydt = [y1*1j]
- return dydt
-
- # 设置初始条件
- y0 = [1+0j]
-
- # 设置时间范围
- tmax=10
- t_span = [0, tmax]
- t2 = np.linspace(0,tmax,100)
- # 求解常微分方程组
- sol = solve_ivp(equations, t_span, y0,method='RK45',t_eval=t2)
-
- # 绘制y-t图像
- plt.plot(sol.t, np.real(sol.y[0]), label='y1')
- plt.xlabel('t')
- plt.ylabel('y')
- plt.legend()
- plt.show()

输出结果是y1的实部:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。