我想要解这个微分方程:y‘’+2y‘+2y=cos(2x),初始条件是:
它的代码是:
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
def dU_dx(U, x):
return [U[1], -2*U[1] - 2*U[0] + np.cos(2*x)]
U0 = [1,0]
xs = np.linspace(0, 10, 200)
Us = odeint(dU_dx, U0, xs)
ys = Us[:,0]
plt.xlabel("x")
plt.ylabel("y")
plt.title("Damped harmonic oscillator")
plt.plot(xs,ys);我怎么才能实现呢?
发布于 2020-08-24 06:21:10
您的初始条件不是,因为它们在两个不同的点上给出了值。这些都是边界条件。
def bc1(u1,u2): return [u1[0]-2.0,u2[1]-0.5]
def bc2(u1,u2): return [u1[1]-1.0,u2[1]-0.8]
def bc3(u1,u2): return [u1[0]-0.0,u2[0]-1.0]你需要一个BVP求解器来解决这些边值问题。
您可以使用射击方法制作自己的求解器,在第1种情况下,如
def shoot(b): return odeint(dU_dx,[2,b],[1,2])[-1,1]-0.5
b = fsolve(shoot,0)
T = linspace(1,2,N)
U = odeint(dU_dx,[2,b],T)或者使用割线方法代替scipy.optimize.fsolve,因为问题是线性的,这应该在1,最多2个步骤中收敛。
或者您可以使用scipy.integrate.solve_bvp求解器(这可能比问题更新?)。您的任务类似于文档中的示例。注意,ODE函数中的参数顺序是在所有其他求解器中切换的,即使在odeint中,您也可以给出选项tfirst=True。
def dudx(x,u): return [u[1], np.cos(2*x)-2*(u[1]+u[0])]用solve_bvp__生成的解,节点是自动生成的积分区间的细分,它们的密度说明了ODE是如何在那个区域“非平坦”的。

xplot=np.linspace(1,2,161)
for k,bc in enumerate([bc1,bc2,bc3]):
res = solve_bvp(dudx, bc, [1.0,2.0], [[0,0],[0,0]], tol=1e-5)
print res.message
l,=plt.plot(res.x,res.y[0],'x')
c = l.get_color()
plt.plot(xplot, res.sol(xplot)[0],c=c, label="%d."%(k+1))用打靶法生成的解,以x=0处的初始值作为未知参数,得到区间[0,3]__的解轨迹。

x = np.linspace(0,3,301)
for k,bc in enumerate([bc1,bc2,bc3]):
def shoot(u0): u = odeint(dudx,u0,[0,1,2],tfirst=True); return bc(u[1],u[2])
u0 = fsolve(shoot,[0,0])
u = odeint(dudx,u0,x,tfirst=True);
l, = plt.plot(x, u[:,0], label="%d."%(k+1))
c = l.get_color()
plt.plot(x[::100],u[::100,0],'x',c=c)发布于 2018-04-22 10:29:06
您可以使用scipy.integrate.ode函数,这类似于scipy.integrate.odeint,但允许jac参数为df/dy,或者在给定of /dx的情况下允许使用jac参数。
https://stackoverflow.com/questions/49964702
复制相似问题