# Secant method

### Visual Basic .NET

''' <summary>
''' Calculates a solution to the equation f(x) = 0 using the secant method
''' </summary>
''' <param name="f">Function f</param>
''' <param name="x0">First trial x value near solution</param>
''' <param name="x1">Second trial x value near solution</param>
''' <returns>x</returns>
Public Function secantMethod(f As Func(Of Double, Double),
x0 As Double,
x1 As Double) As Double

If x0 = x1 Then
If f(x0) = 0 Then
Return x0
Else
Throw New System.Exception("Secant method requires x0 <> x1")
End If
End If

Dim xOfNminus2 As Double = x0
Dim xOfNminus1 As Double = x1

Dim fOfxOfNminus2 As Double = f(xOfNminus2)
Dim fOfxOfNminus1 As Double = f(xOfNminus1)

Dim xn As Double = xOfNminus2
Dim fOfxn As Double

For i As Integer = 1 To 100

If xOfNminus1 = xOfNminus2 OrElse fOfxOfNminus1 = fOfxOfNminus2 Then Exit For

xn = xOfNminus1 - fOfxOfNminus1 * (xOfNminus1 - xOfNminus2) /
(fOfxOfNminus1 - fOfxOfNminus2)

fOfxn = f(xn)

If fOfxn = 0 Then Exit For

xOfNminus2 = xOfNminus1
xOfNminus1 = xn
fOfxOfNminus2 = fOfxOfNminus1
fOfxOfNminus1 = fOfxn

Next

Return xn

End Function

#### Example usage

To find the solution of the equation $$\tan x = x$$ between $$4.4$$ and $$4.5$$ rearrange as an expression equal to zero ($$\tan x - x = 0$$) and call as follows:

secantMethod(Function(x) Math.Tan(x) - x, 4.4, 4.5)