Skip to main content
 首页 » 编程设计

python之运行 Python 脚本, 'Memory error', 'for' 循环

2025年05月04日9davidwang456

我正在尝试对三体问题建模,其中我有三个广义坐标(一个径向坐标和两个角坐标)和三个二阶(耦合)微分方程。我想看看系统在改变初始条件 rho[0] 时如何演化。 我的脚本有什么问题吗?上面已经很好地定义了变量和参数,因此我将省略它们;这是代码:

    for i in range(1000000,10000000,1000000): 
        rho[0] = i 
 
        rho[1] = rho[0] + vrho*dt 
        theta[1] = theta[0] + vtheta*dt #angulos radianes 
        phi[1] = phi[0] + vphi*dt 
 
        for t in range(1, N-1): 
        #Velocidades de las coordenadas 
            v[0,t-1] = (rho[t] - rho[t-1])/dt 
            v[1,t-1] = (theta[t] - theta[t-1])/dt 
            v[2,t-1] = (phi[t] - phi[t-1])/dt 
 
        #"Ecuaciones diferenciales" 
            rho[t+1] = (2*rho[t] - rho[t-1]) + (rho[t]*(v[2,t-1]**2) - G*M/(rho[t]**2) - (9*G*M*((np.cos(theta[t]-phi[t]))**2)*(l**2))/(8*(rho[t]**4)))*(dt**2) 
            theta[t+1] = (2*theta[t] - theta[t-1]) + ((-3*G*M*np.sin(2*(theta[t]-phi[t])))/(2*(rho[t]**3)))*(dt**2) 
            phi[t+1] = (2*phi[t] - phi[t-1]) + ((3*G*M*np.sin(2*(theta[t]-phi[t]))*(l**2))/(8*(rho[t]**5)) - (2*v[0,t-1]*v[2,t-1])/(rho[t]))*(dt**2) 
 
            for j in range(0,N): 
                x[j] = rho[j]*np.cos(phi[j]) 
                y[j] = rho[j]*np.sin(phi[j]) 
 
                plt.plot(x,y) 

这是错误:

--------------------------------------------------------------------------- 
    MemoryError                               Traceback (most recent call last) 
<ipython-input-3-4c789e1dfc65> in <module>() 
     21             y[j] = rho[j]*np.sin(phi[j]) 
     22  
---> 23             plt.plot(x,y) 

我试图做的是让 python 求解不同初始条件下的 ODE,保存 rho、theta、phi 和 V 向量以便操纵它们。考虑到我想要 body 的轨迹,对于 rho 和 phi 的那些值,我想将它们转换为笛卡尔坐标,绘制轨迹,然后使用 rho 的下一个初始条件重新启动 ODE。

我不得不引入 j 计数器,因为 x 和 y 被定义为 np.zeros(N) 以匹配 rho、theta 和 phi 的维度。计数器代表这种向量的位置,其思想是对于 rho 和 phi 中的每个位置,笛卡尔等价物保存在相同的位置。由于 t 上升到 N-1,因此最后可用的 t 是 N-2,我不知道如何避免添加另一个;为了解决起点差,我可以写最后一个'for' switching j for t-1,但这不会导致维度错误吗?

请您参考如下方法:

你能试试下面的代码吗:

for i in range(1000000,10000000,1000000): 
    rho[0] = i 
 
    rho[1] = rho[0] + vrho*dt 
    theta[1] = theta[0] + vtheta*dt #angulos radianes 
    phi[1] = phi[0] + vphi*dt 
 
    for t in range(1, N-1): 
        # Velocidades de las coordenadas 
        v[0,t-1] = (rho[t] - rho[t-1])/dt 
        v[1,t-1] = (theta[t] - theta[t-1])/dt 
        v[2,t-1] = (phi[t] - phi[t-1])/dt 
 
        # "Ecuaciones diferenciales" 
        rho[t+1] = (2*rho[t] - rho[t-1]) + (rho[t]*(v[2,t-1]**2) - G*M/(rho[t]**2) - (9*G*M*((np.cos(theta[t]-phi[t]))**2)*(l**2))/(8*(rho[t]**4)))*(dt**2) 
        theta[t+1] = (2*theta[t] - theta[t-1]) + ((-3*G*M*np.sin(2*(theta[t]-phi[t])))/(2*(rho[t]**3)))*(dt**2) 
        phi[t+1] = (2*phi[t] - phi[t-1]) + ((3*G*M*np.sin(2*(theta[t]-phi[t]))*(l**2))/(8*(rho[t]**5)) - (2*v[0,t-1]*v[2,t-1])/(rho[t]))*(dt**2) 
 
    for j in range(0,N): 
        x[j] = rho[j]*np.cos(phi[j]) 
        y[j] = rho[j]*np.sin(phi[j]) 
 
    plt.plot(x,y) 

我认为在绘图阶段有一些错误的缩进,这意味着每次你想要绘制一条线时,你实际上是在绘制 N ^ 2 行!