VBA实现的辛普森积分法源代码

分类:代码, 博客 标签:

辛普森积分法(Simpson Integration)是一类常用且有效的数值积分法中,这里水文工具集提供一个使用VBA实现的辛普森积分法,并且给出源代码,使用时注意要把代码里面的FUNC_STR_NAME替换成你所要求积的函数名称,具体代码如下:

Option Explicit
Option Base 1
'================================
' 辛普森积分法
' Simpson_Integral_Func
' http://www.cnhup.com
'================================
Function Simpson_Integral_Func( _
         ByRef Lower_Bound As Double, _
         ByRef Upper_Bound As Double, _
         Optional ByRef epsilon As Double = 2 ^ -52)

    Dim i As Long
    Dim j As Long

    Dim X_VAL As Double

    Dim S1_VAL As Double
    Dim S2_VAL As Double
    Dim S3_VAL As Double
    Dim S4_VAL As Double

    Dim Delta_VAL As Double
    Dim Result_VAL As Double

    On Error GoTo ERROR_HANDEL_LABEL

    S3_VAL = 1#
    Delta_VAL = Upper_Bound - Lower_Bound
    S1_VAL = FUNC_STR_NAME(Lower_Bound) + _
             FUNC_STR_NAME(Upper_Bound)

    i = 0
    Do
        S4_VAL = S3_VAL
        Delta_VAL = Delta_VAL / 2#
        S2_VAL = 0#
        X_VAL = Lower_Bound + Delta_VAL
        j = 0
        Do
            S2_VAL = S2_VAL + 2# * FUNC_STR_NAME(X_VAL)
            X_VAL = X_VAL + 2# * Delta_VAL
            j = j + 1
        Loop Until Not X_VAL < Upper_Bound
        S1_VAL = S1_VAL + S2_VAL
        S3_VAL = (S1_VAL + S2_VAL) * Delta_VAL / 3#
        X_VAL = Abs(S4_VAL - S3_VAL) / 15#
        i = i + 1
    Loop Until Not X_VAL > epsilon
    Result_VAL = S3_VAL

    Simpson_Integral_Func = Result_VAL

    Exit Function
ERROR_HANDEL_LABEL:
    Simpson_Integral_Func = Err.Number
End Function


分类:代码, 博客 标签:

发表评论

You must be logged in to post a comment.