使用多步求解器求解ode

时间:2013-05-26 06:09:39

标签: python numpy ode

以下是目前为止多个解算器的代码。 这个问题的系统在这里,our system 但是,当我在Python中执行它时,它会向我显示以下错误:

追踪(最近一次通话): 文件“G:\ math3511 \ assignment \ assignment5 \ qu2”,第59行,in X = AdamsBashforth4(等式,init,t) AdamsBashforth4中的文件“G:\ math3511 \ assignment \ assignment5 \ qu2”,第32行 k2 = h * f(x [i] + 0.5 * k1,t [i] + 0.5 * h) TypeError:不能将序列乘以'float'

类型的非int

代码:

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)

1 个答案:

答案 0 :(得分:0)

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

Dirk是对的,看着你的算法,你的等式应该返回(即使它很小)一个numpy数组,因为你可以标量乘以一个numpy数组。因此,保留您的代码,但将返回值与数组嵌入等式中。像这样:

np.array([1,2]) # a numpy array containing [1,2]