python - 相空间中的轨迹 - 溢出错误 : (34, 'Result too large' )

标签 python ode

我是 Python 的新手,但我之前有使用 C++ 和 MATLAB 的经验。 我目前正在编写一个程序来绘制涉及 dy/dt 和 dx/dt 的非线性系统在相空间中的轨迹。但是,对于更复杂的函数形式,我收到了溢出错误。我有什么办法可以避免这个问题吗?提前致谢!

这些是我的代码:

fig = plt.figure(figsize=(18,6))
dt = 0.01
def trajectories():
    #initial conditions
    x = y = 0.1
    xresult = [x]
    yresult = [y]
    for t in xrange(10000):
        # functional form: dx/dt = y, dy/dt = -r(x**2-1)*y-x
        nextx = x + (r*x-y+x*y**2) * dt
        nexty = y + (x + r*y + y**3) * dt
        x, y = nextx, nexty
        xresult.append(x)
        yresult.append(y)
    plt.plot(xresult, yresult)
    plt.axis('image')
    plt.axis([-3, 3, -3, 3])
    plt.title('r = ' + str(r))


rs = [-1, -0.1, 0, .1, 1]
for i in range(len(rs)):
    fig.add_subplot(1, len(rs), i + 1)
    r = rs[i]
    trajectories()
plt.show()

EDIT: this is the full traceback
Traceback (most recent call last):
  File "/Users/Griffin/Atom/NumInt.py", line 33, in <module>
    trajectories()
  File "/Users/Griffin/Atom/NumInt.py", line 18, in trajectories
    nextx = x + (r*x-y+x*y**2) * dt
OverflowError: (34, 'Result too large')

最佳答案

您的直接错误与您用于积分的欧拉算法在您使用的步长下变得不稳定这一事实有关。最终的问题实际上是使用欧拉算法。下面的代码使用 scipy.integrate.odeint 来处理集成,并且由于能够执行可变步长而做得更好。有些集成还不完善,但至少我们得到了一些结果。

import numpy
import scipy.integrate
import matplotlib.pyplot as plt

def derivatives(states, t, r):
    x, y = states
    return [r*x - y + x*y**2,
            x + r*y + y**3]

def trajectories(r):
    initial_conditions = [0.1, 0.1]
    times = numpy.linspace(0, 100, 1000)
    result = scipy.integrate.odeint(derivatives, initial_conditions, times, args=(r,))
    xresult, yresult = result.T

    plt.plot(xresult, yresult)
    plt.axis('image')
    plt.axis([-3, 3, -3, 3])
    plt.title('r = ' + str(r))

fig = plt.figure(figsize=(18,6))

rs = [-1, -0.1, 0, .1, 1]

for i, r in enumerate(rs, 1):  # Avoid for i in range(len(rs))
    fig.add_subplot(1, len(rs), i)
    trajectories(r)
plt.show()

结果:

result of simulation

关于python - 相空间中的轨迹 - 溢出错误 : (34, 'Result too large' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46836227/

相关文章:

python - 使用 Pandas DataFrames 比较两个标题不同但行数据相同的 excel 文件

python - PySpark Dataframe 根据其他列中的重复值识别一列上的不同值

r - 常微分方程 (ODE) - 有什么方法可以防止出现负值吗?

c++ - 无法获得 Matlab 生成的相同结果

python - 如何使用Python求解具有边界条件的微分方程,其中一个是不等式

python - 我的快速排序因大小为 2^13 的列表而挂起

python - 使用 Array 或 Series 从多列中进行选择

python - 基于Python中的匹配列表连接两个矩阵?

r - 有没有办法强制 ode() [deSolve-R 包] 在 ode 函数中的每个积分步骤提供输出

c++ - 使用 C++ 求解二阶 ODE 的 Runge-Kutta 四阶