0

以下是迄今为止多个求解器的代码。这个问题的系统在这里,我们的系统 但是,当我在Python中执行它时,它显示了以下错误:

Traceback(最近一次调用最后):文件“G:\math3511\assignment\assignment5\qu2”,第 59 行,在 X = AdamsBashforth4(equation, init, t) 文件“G:\math3511\assignment\assignment5\qu2”中,第 32 行,在 AdamsBashforth4 k2 = h * f( x[i] + 0.5 * k1, t[i] + 0.5 * h ) TypeError: can't multiply sequence by non-int of type '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)
4

1 回答 1

0

似乎 f 正在返回一个序列(列表、元组等),并且没有将序列中的所有项目乘以一个值的操作。

Dirk 是对的,看看你的算法,你的方程应该返回(即使它很小)一个 numpy 数组,因为你可以标量乘以一个 numpy 数组。所以保留你的代码,但将你的回报嵌入到一个数组的方程中。像这样:

np.array([1,2]) # a numpy array containing [1,2]
于 2013-05-26T06:15:20.563 回答