我在数值求解一阶微分方程组的x(t)。系统是:
dy/dt=(C)\*[(-K\*x)+M*A]
为了解决这个问题,我实现了如下的正向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欧拉(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 )
我的目标是绘制函数。
问题是你的线路
在这里,您将x定义为-200.0的单个项数组。你可以这样做:
或者这个:
注意:你们的进口货很混乱。在报头中导入numpy模块三次,然后导入pylab(已经包含所有numpy模块)。如果你想轻松一点
最上面的一行你可以使用所有你需要的模块。
正如回溯所说,问题来自行
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.append(x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] ))
替换x[i+1] = x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] )
。相关问题 更多 >
编程相关推荐