我在写一个用Python解决二阶微分方程的程序时遇到了一些麻烦。我的问题似乎是试图在
t
中包含
p(t)
函数的返回值,它输出一个数组。如果我把
dU_dx
函数中的'p'替换为
p(t)
函数本身的输出(本例中为
-2*t
),似乎可以正常工作。否则,我得到的错误是
"用一个序列设置一个数组元素。请求的数组在1维之后有一个不均匀的形状。检测到的形状是(2,)+不均匀部分"
如果能帮助我找出如何编辑我的代码以解决数组问题,我将不胜感激。
这个函数解决了微分方程
x'' + px' + qx = 0
。这里,
q
和
p
是
t
的函数。
它是在区间
[lp, rp]
上解决的。
Inputs:
p
is a function of
t
relating to (in front of)
x'
q
is a function of
t
relating to (in front of)
x
lp
is the lower time boundary
rp
is the upper time boundary
x0
is an initial
x
value
x0p
is an initial
x'
value
h
is a step size
Outputs:
T
is the vector of times
X
the approximate solution evaluated at the elements of
T
def my_sode(p, q, lp, rp, x0, x0p, h):
#You may not modify any code above this line
T = arange(lp, rp + h, h)
p = p(T)
q = q(T)
t = T
def dU_dx(U, t):
return [U[1], -(p) * U[1] - (q)*U[0]]
U0 = [x0, x0p]
Us = odeint(dU_dx, U0, T)
X = Us[:,0]
#You cannot modify anything below this line!
return T, X
Using this block of code works fine.
def p(t):
return 0
def q(t):
return 1
# this is the actual solution
def sol(t):
return sin(t)
x0 = 0
x0p = 1
lp = 0
rp = pi
Tt = linspace(lp, rp, 10)
plt.figure()
T1, X1 = my_sode(p,q, lp, rp, x0, x0p, .2)
T2, X2 = my_sode(p,q, lp, rp, x0, x0p, .1)
plt.plot(Tt, sol(Tt), 'r*', T1, X1, 'b:', T2, X2,'g')
This block of code produces the error.
def p(t):
return -2 * t
def q(t):
return 2
# this is the actual solution
def sol(t):
return t
x0 = 0
x0p = 1
lp = 0
rp = 1
Tt = linspace(lp, rp, 10)