Mark.R
Mark.R

Reputation: 415

Scaled Complementary Error Function, erfcx(x), computation avoiding arithmetic overflow - VBA/Excel

I need an algorithm/approximation to compute the Scaled Complementary Error Function, erfcx(x) to double-float precision.

I'm on a work PC so I’m limited to using Excel and VBA and I cannot use external libraries or add-ins: I need to code this myself.

Excel only provides erf() and erfc() functions.

The relationship erfcx(x) = exp(x^2) erfc(x) is obviously useful, however there is arithmetic over/underflow for x larger than around 26.5 and I need to go larger than this.

The below post discussed a python implementation – but it doesn’t seem to resolve the issue from what I can tell. It provides solutions using other libraries or an approximation that isn’t precise enough for my needs.

Is there a scaled complementary error function in python available?

Any suggestions?

Update:

I used this Continued Fraction representation I found on Wikipedia
and a modified version of the algorithm for solving continued fractions found here http://finance4traders.blogspot.nl/2009/07/continued-fractions-and-modified-lentzs.html

The following code seems to work and actually takes fewer iterations for larger input parameters.

Function erfcx(x) As Variant
Dim Ai As Double
Dim Bi As Double
Dim Ci As Double
Dim Di As Double
Dim Ei As Double
Dim Fi As Double
Dim X2 As Double
Dim i As Long

Const SQRPI As Double = 1.7724538509055
Const MAX_ITERATIONS = 1000


If x < 26.5 Then
    erfcx = Application.WorksheetFunction.ErfC_Precise(x) * Exp(x ^ 2)
Else
    X2 = x ^ 2
    Bi = X2
    Fi = X2
    Ci = X2
    Di = 0
    Do
        i = i + 1
        Ai = i / 2
        If i Mod 2 = 0 Then
            Bi = X2
        Else
            Bi = 1
        End If
        Di = 1 / (Bi + Ai * Di)
        Ci = Bi + Ai / Ci
        Ei = Ci * Di
        Fi = Fi * Ei
    Loop While Ei <> 1 And i < MAX_ITERATIONS
    Debug.Print i
    erfcx = x / Fi / SQRPI
End If  End function

Upvotes: 1

Views: 745

Answers (1)

Gary&#39;s Student
Gary&#39;s Student

Reputation: 96753

Several approximations are discuss here:

AMS Journal Article

Once you have determined which approximation is suitable, we can help you code it in either a worksheet function or a VBA UDF()

Upvotes: 0

Related Questions