2017-10-19 122 views
3

我是Python新手,但我在C++和MATLAB方面擁有豐富的經驗。 我目前正在編寫一個程序來繪製包含dy/dt和dx/dt的非線性系統在相空間中的軌跡。但是,對於更復雜的功能表單,我收到了溢出錯誤。有什麼辦法可以繞過這個問題嗎?提前致謝!相空間中的軌跡 - Overflowerror:(34,'結果太大')

這是我的代碼:

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') 
+0

請張貼完整回溯 – roganjosh

+0

剛剛添加的全回溯。謝謝! – griffinleow

+0

你的郵政編碼適合我。我在想你的數據的小數精度....你的dt固定爲0.01?低值會發生什麼? – eduardosufan

回答

2

您即時錯誤與您正在使用集成歐拉算法成爲你正在使用的步長不穩定的事實做。最終的問題實際上是使用歐拉算法。下面的代碼使用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