Passing function as an argument in VBA eg. root finding

I am looking for a way to pass a function as an argument.

Say I have function with a root finding algorithm. This function finds the root of another function f(). Now I want to be able to pass any function as an argument so that I can use the rootFinder function with different functions (ie. any of the n amount of functions I have defined)

How can I pass f() and it's respective inputs as an argument?

Here is my code to illustrate the question. I have used f() and functionInputs as placeholders.

Function rootFinder(ByVal lowBound As Double, ByVal upBound As Double, ByVal f() As String, ByVal functionInputs As String)
'this function uses the
Dim xmid As Double, xold As Double, tol As Double

'accuary of algorithm
tol = 0.001

If f(lowBound,functionInputs) * f(upBound,functionInputs) > 0 Then
    MsgBox "choose other bounds"
Else
        xold = lowBound
    Do
        xmid = (lowBound + upBound) / 2
        If Abs((xmid - xold) / xmid) < tol Then
            Exit Do
        End If
        xold = xmid
        If f(lowBound,functionInputs) * f(xmid,functionInputs) > 0 Then
            lowBound = xmid
        Else
            upBound = xmid
        End If
    Loop
    rootFinder = xmid
End If

End Function

Upvotes: 2

Views: 138

Answers (1)

Robin Hartland
Robin Hartland

Reputation: 336

The f() "function" the rootFinder function takes as a parameter is actually an array of strings the way you've declared it. I don't think you can pass a function as a parameter like you want to. Why don't you just use the function's actual name and call it normally (not trying to pass it as a parameter) ?

(Your algorithm is very clever and slick though. I hope you get it working!)

Upvotes: 1

Related Questions