python - 用 scipy odeint 在 python 中求解向量常微分方程

标签 python vector matplotlib scipy ode

我正在尝试解决涉及向量的问题,但无法得出可行的答案。所以我将它分成 6 个分量,一个分量的每个时间导数一个,速度分量的每个时间导数一个分量。第一个值似乎是合理的,但随后它会跳到数百万,我不确定为什么。老实说,我一开始并不确定如何做到这一点,现在只是试一试。我似乎无法在网上找到任何信息,如果有此类问题的示例,我可以使用一些帮助或一些链接。任何有关如何使用它来求解 ODE 的信息都将不胜感激。

def dr_dt(y, t):
"""Integration of the governing vector differential equation.
d2r_dt2 = -(mu/R^3)*r with d2r_dt2 and r as vecotrs.
Initial position and velocity are given.
y[0:2] = position components
y[3:] = velocity components"""

    G = 6.672*(10**-11)
    M = 5.972*(10**24)
    mu = G*M
    r = np.sqrt(y[0]**2 + y[1]**2 + y[2]**2) 

    dy0 = y[3]
    dy1 = y[4]
    dy2 = y[5]
    dy3 = -(mu / (r**3)) * y[0]
    dy4 = -(mu / (r**3)) * y[1]
    dy5 = -(mu / (r**3)) * y[2]
    return [dy0, dy3, dy1, dy4, dy2, dy5]

解决了这个问题之后,我想绘制它。它应该变成一个椭圆,但老实说,我也不确定该怎么做。我正在考虑获取位置的大小,然后随时间绘制它。如果有更好的方法,请随时告诉我。

谢谢。

最佳答案

首先,如果您的 y[:3] 是位置并且 y[3:] 是速度,那么 dr_dt 函数应该返回组件完全按照这个顺序。其次,要绘制轨迹,我们可以使用优秀的 matplotlib mplot3d 模块,或者省略位置和速度的第 z 分量(因此我们的运动在 XY 平面上),然后绘制yx。示例代码(修正了返回值的顺序)如下:

import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint

def dr_dt(y, t):
    """Integration of the governing vector differential equation.
    d2r_dt2 = -(mu/R^3)*r with d2r_dt2 and r as vecotrs.
    Initial position and velocity are given.
    y[0:2] = position components
    y[3:] = velocity components"""

    G = 6.672*(10**-11)
    M = 5.972*(10**24)
    mu = G*M
    r = np.sqrt(y[0]**2 + y[1]**2 + y[2]**2).

    dy0 = y[3]
    dy1 = y[4]
    dy2 = y[5]
    dy3 = -(mu / (r**3)) * y[0]
    dy4 = -(mu / (r**3)) * y[1]
    dy5 = -(mu / (r**3)) * y[2]
    return [dy0, dy1, dy2, dy3, dy4, dy5]

t = np.arange(0, 100000, 0.1)
y0 = [7.e6, 0., 0., 0., 1.e3, 0.]
y = odeint(dr_dt, y0, t)
plt.plot(y[:,0], y[:,1])
plt.show()

这会产生一个漂亮的椭圆:

enter image description here

关于python - 用 scipy odeint 在 python 中求解向量常微分方程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32622230/

相关文章:

python - 在 python 中创建一个简单的数字模式?

c++ - 从 char * 中的整数填充 vector<int>

python - 为什么 RestrictedPython 在与 Python 3.6 一起使用时表现不同?

r - 提取向量的每个第 n 个元素

c++ - 在指向对象的指针 vector 上的 for 循环中的段错误

Python 如何设置 matplotlib 图的轴

python - 使用 Python/Matplotlib 基于颜色图绘制(极坐标)色轮

python - python 中的热图 - 带颜色

Python - 在 z 平面上切片

python - 替换所有连续重复的字母忽略特定单词