我是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')
答案 0 :(得分:2)
您的即时错误与您使用的Euler算法在您使用的步长上变得不稳定这一事实有关。最终的问题实际上是使用欧拉算法。下面的代码使用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()
结果: