我對數值求解x(t)的一階微分方程組。該系統是: 這裏是我的代碼:IndexError:索引1超出軸1的大小1/ForwardEuler
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
dy/dt=(C)\*[(-K\*x)+M*A]
我已經實現了向前歐拉方法如下解決這個問題
我不明白什麼可能是錯誤的。我已經解決了問題後,已經擡頭看,但它並沒有幫助我。你可以找到我的錯誤? 我使用下面的代碼爲取向: 高清歐拉(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 = np.array([x0 * n])'產生一個元素的數組。你想做什麼? – mdurant