我正在对一阶微分方程组的x(t)进行数值求解。系统是:dy/dt=(C)\*[(-K\*x)+M*A]
我已经实现了Forward Euler方法来解决此问题,如下所示:
这是我的代码:
import matplotlib
import numpy as np
from numpy import *
from numpy import linspace
from matplotlib import pyplot as plt
C=3
K=5
M=2
A=5
#------------------------------------------------------------------------------
def euler (f,x0,t):
n=len (t)
x=np.array ([x0*n])
for i in xrange (n-1):
x[i+1] = x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] )
return x
#---------------------------------------------------------------------------------
if __name__=="__main__":
from pylab import *
def f(x,t):
return (C)*[(-K*x)+M*A]
a,b=(0.0,10.0)
n=200
x0=-1.0
t=linspace (a,b,n)
#numerical solutions
x_euler=euler(f,x0,t)
#compute true solution values in equal spaced and unequally spaced cases
x=-C*K
#figure
plt.plot (t,x_euler, "b")
xlabel ()
ylabel ()
legend ("Euler")
show()
`
M=2
A=5
#----------------------------------------------------------------------------
def euler (f,x0,t):
n=len (t)
x=np.array ([x0*n])
for i in xrange (n-1):
x[i+1] = x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] )
return x
#---------------------------------------------------------------------------
if __name__=="__main__":
from pylab import *
def f(x,t):
return (C)*[(-K*x)+M*A]
a,b=(0.0,10.0)
n=200
x0=-1.0
t=linspace (a,b,n)
#numerical solutions
x_euler=euler(f,x0,t)
#compute true solution values in equal spaced and unequally spaced cases
x=-C*K
#figure
plt.plot (t,x_euler, "b")
xlabel ()
ylabel ()
legend ("Euler")
show()
我得到以下跟踪:
Traceback (most recent call last):
File "C:/Python27/testeuler.py", line 50, in <module>
x_euler=euler(f,x0,t)
File "C:/Python27/testeuler.py", line 28, in euler
x[i+1] = x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] )
IndexError: index 1 is out of bounds for axis 0 with size 1
我不明白这可能是什么问题。我已经在解决问题后抬头,但这无济于事。您能找到我的错误吗?
我正在使用以下代码作为方向:
def euler(f,x0,t):
n = len( t )
x = numpy.array( [x0] * n )
for i in xrange( n - 1 ):
x[i+1] = x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] )
return x
if __name__ == "__main__":
from pylab import *
def f( x, t ):
return x * numpy.sin( t )
a, b = ( 0.0, 10.0 )
x0 = -1.0
n = 51
t = numpy.linspace( a, b, n )
x_euler = euler( f, x0, t )
我的目标是绘制函数。
最佳答案
正如Traceback所说,问题来自x[i+1] = x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] )
行。让我们在上下文中替换它:
i + 1 >= len(x)
i >= 0
,元素x[i+1]
不存在。在这里,此元素自开始以来就不存在。 for循环。要解决此问题,必须将
x[i+1] = x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] )
替换为x.append(x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] ))
。关于python - IndexError:索引1超出了大小为1/ForwardEuler的轴0的范围,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30059227/