以下是到目前为止多个解算器的代码。解决这个问题的系统在这里,但是,当我在our system中执行它时,它显示了以下错误:
回溯(最近一次调用):文件“G:\math3511\Assignment5\qu2”,第59行,在X= AdamsBashforth4 (等式,初始化,t)文件“G:\math3511\Assignment5\qu2”,第32行,in AdamsBashforth4 k2 =h* f( xi + 0.5 * k1,ti + 0.5 *h) TypeError:不能将序列乘以'float‘类型的非整数
代码:
import numpy
from numpy import array, exp, linspace
def AdamsBashforth4( f, x0, t ):
"""
Fourth-order Adams-Bashforth method::
u[n+1] = u[n] + dt/24.*(55.*f(u[n], t[n]) - 59*f(u[n-1], t[n-1]) +
37*f(u[n-2], t[n-2]) - 9*f(u[n-3], t[n-3]))
for constant time step dt.
RK2 is used as default solver for first steps.
"""
n = len( t )
x = numpy.array( [ x0 ] * n )
# Start up with 4th order Runge-Kutta (single-step method). The extra
# code involving f0, f1, f2, and f3 helps us get ready for the multi-step
# method to follow in order to minimize the number of function evaluations
# needed.
f1 = f2 = f3 = 0
for i in xrange( min( 3, n - 1 ) ):
h = t[i+1] - t[i]
f0 = f( x[i], t[i] )
k1 = h * f0
k2 = h * f( x[i] + 0.5 * k1, t[i] + 0.5 * h )
k3 = h * f( x[i] + 0.5 * k2, t[i] + 0.5 * h )
k4 = h * f( x[i] + k3, t[i+1] )
x[i+1] = x[i] + ( k1 + 2.0 * ( k2 + k3 ) + k4 ) / 6.0
f1, f2, f3 = ( f0, f1, f2 )
for i in xrange( n - 1 ):
h = t[i+1] - t[i]
f0 = f( x[i], t[i] )
k1 = h * f0
k2 = h * f( x[i] + 0.5 * k1, t[i] + 0.5 * h )
k3 = h * f( x[i] + 0.5 * k2, t[i] + 0.5 * h )
k4 = h * f( x[i] + k3, t[i+1] )
x[i+1] = x[i] + h * ( 9.0 * fw + 19.0 * f0 - 5.0 * f1 + f2 ) / 24.0
f1, f2, f3 = ( f0, f1, f2 )
return x
def equation(X, t):
x, y = X
return [ x+y-exp(t), x+y+2*exp(t) ]
init = [ -1.0, -1.0 ]
t = linspace(0, 4, 50)
X = AdamsBashforth4(equation, init, t)发布于 2013-05-26 14:15:21
似乎f返回的是一个序列(列表、元组等),并且没有将序列中的所有项与值相乘的操作。
Dirk是对的,看看你的算法,你的等式应该返回一个numpy数组(即使它很小),因为你可以标量乘一个numpy数组。所以保留你的代码,但是把你的返回值嵌入到带有数组的方程式中。如下所示:
np.array([1,2]) # a numpy array containing [1,2]https://stackoverflow.com/questions/16756700
复制相似问题