如何解决微分方程中的索引误差?

时间:2018-11-09 20:37:00

标签: python differential-equations

我正在尝试创建一个使用后向差分解决质量弹簧阻尼器系统的程序,唯一的问题是我遇到了不确定的索引错误,我不确定如何解决:

import numpy as np 
import matplotlib.pyplot as plt

def MSD_Solver(m,b,K):
    #input: m = mass, b = damping ratio, K = spring constant
    #output: (t,x) time vs position

    tinitial = 0
    tfinal = 15
    step = .005

    t = np.linspace(tinitial,tfinal,step)

    x = np.zeros_like(t)

    x[0]=0
    x[1]=0
    for k in range (len(t)-1):            # extra element so subtract by 1
        x[k] = (t**2)/((m+b)*t+(t**2)*k) + (x[k-2](-m))/((m+b)*t+(t**2)*k) + (x[k-1]((2*m)+(b*t)))/((m+b)*t+(t**2)*k)
    return plt.plot(t,x)

print(MSD_Solver(1,.5,5)),MSD_Solver(1,1,5),MSD_Solver(1,2,5)
plt.show()

2 个答案:

答案 0 :(得分:2)

linspace doc显示第三个参数是项目数,而不是步骤数。您的step值被截断为0,因此返回的t数组为空。结果,x没有元素,并且x[0]超出范围。

尝试一下:

tinitial = 0
tfinal = 15
step = .005
num = (tfinal - tinitial) / step + 1

t = np.linspace(tinitial,tfinal,num)

这将使您了解复杂计算中的语义错误。

答案 1 :(得分:1)

您可能想(?)使用一阶和二阶差商离散化

m*x''(t) + b*x'(t) + K*x(t) = 1

m*(x[j+1]-2*x[j]+x[j-1]) + 0.5*dt*b*(x[j+1]-x[j-1]) + dt^2*K*x[j] = dt**2

这样

x[j+1] = ( dt**2 + (2*m-K*dt**2)*x[j] - (m-0.5*dt*b)*x[j-1] ) / (m+0.5*dt*b)

在代码中

def MSD_Solver(m,b,K):
    #input: m = mass, b = damping ratio, K = spring constant
    #output: (t,x) time vs position

    tinitial = 0
    tfinal = 15
    step = .005

    t = np.arange(tinitial,tfinal,step)
    x = np.zeros_like(t)

    dt = t[1]-t[0]  # use the actual time step
    x[0:2] = [ 0, 0]
    for j in range(1,len(t)-1):
        x[j+1] = ( dt**2 + (2*m-K*dt**2)*x[j] - (m-0.5*dt*b)*x[j-1] ) / (m+0.5*dt*b)
    return t,x

t,x = MSD_Solver(1,.5,5)        
plt.plot(t,x); plt.show();

plot of solution