我正在数值求解一阶微分方程组的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 …Run Code Online (Sandbox Code Playgroud) 我刚开始用Python编程,对Numpy软件包很新......我仍然试图了解它.我试图用euler方法解决一个函数.
这是我的代码:
Z=4
B=8
U=1
C=4
a,b=(0.0,10.0)
n=2000
x0=-1.0
t=linspace (a,b,n)
#-----------------------------------------------------------------------------
def euler (f,x0,t):
n=len (t)
x=np.array(n*[x0,])
for i in xrange (n-1):
float (x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] ))
return x
#---------------------------------------------------------------------------------
if __name__=="__main__":
def f(x,t):
return float((Z)*[-(1/6)*B*C*x^3+0.5*U*t^2])
#numerical solutions
x_euler=euler(f,x0,t)
#figure
plt.plot (t,x_euler, "b")
xlabel (t)
ylabel (x)
legend ("Euler")
show()
Run Code Online (Sandbox Code Playgroud)
对于这些问题,我不同意类似的解决方案.这是我的追溯:
Traceback (most recent call last):
File "C:\Python27\testeuler.py", line 45, in <module>
x_euler=euler(f,x0,t)
File "C:\Python27\testeuler.py", line 31, in euler
float (x[i] …Run Code Online (Sandbox Code Playgroud)