I'm doing a root finder using Newton's Method and it will run fine in my spreadsheet but when I do a step through i get an overflow runtime error and I'm not sure why. I've tried changing the variables from double to long but it doesn't seem to help.
I'm pretty new to this, any help would be appreciated.
Code:
Option Explicit
Sub NewtonMethod()
' Newton Method Macro to find roots of f(x)= 5-x-ln(x)
Dim xi As Double
' First guess of x
Dim xii As Double
' value of function with x = first guess
Dim xiii As Double
'value of first derivative of function with x = first guess
Dim tol As Double
' tolerance of calculation to see if solution fits into parameters
Dim i As Integer
' counter to stop loop
Dim imax As Integer
' maximim i value
' Initialize Variables
Range("C3").Value = ""
' found root value will print to the right of the word Root in spreadsheet
Range("C4").Value = ""
' number of itterations taken to find root will print to the right of the word Itterations in spreadsheet
tol = Range("A2").Value
xi = Range("A1").Value
i = 0
imax = 100
' Main
Do While (i < imax)
' xii = Root_Function(xi)
xii = (xi - (Root_Function(xi) / Root_Deriv(xi))) ' Error Here!
If (Abs((xi - xii) / xi) < tol) Then
Range("C3").Value = xii
Range("C4").Value = i
Exit Do
Else
xi = xii
i = i + 1
If (i = imax) Then MsgBox "Did not Converge"
End If
Loop
End Sub
' Defines function given in terms of x
Function Root_Function(x As Double) As Double
Root_Function = 5 - x - Log(x)
' Root_Function = 5 - xi - Log(xi)
End Function
' Defines first derivative of function given
Function Root_Deriv(x As Double) As Double
Root_Deriv = -1# / x - 1#
End Function
I'm pretty new to this, any help would be appreciated.