如何修正微分方程中的指标误差?

2024-09-28 17:04:49 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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()

Tags: import程序系统asstepnp质量plt
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)

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

你可能想,用一阶和二阶差商来离散化

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

相关问题 更多 >