lobobunny
12-17-2017, 10:12 AM
Hello! I am trying to write a code to use newtons method to find the root of a function. Newtons method is xnew = x - f(x)/f'(x)
Iterations continue until xnew = 0 within a given tolerance
I wrote a code and my logic seems good to me. I can't find any issues. The program is not giving me any errors, but it will not output anything. I have my output inside the loop. I can't figure out what's wrong. Does anyone see why this is not outputting anything? Please and thank you!
I attached a screenshot of my spreadsheet so you can see how I have it set up.
Thanks so much.
Sub NewtonMethod()
Dim x As Double
Dim xnew As Double
Dim EoverD As Double
Dim Re As Double
Dim ActRow As Integer
Dim FofX As Double
Dim DfDx As Double
Dim Tol As Double
Dim iMax As Integer
Dim i As Integer
Worksheets(ActiveSheet.Name).Activate
iMax = 100
Tol = ActiveSheet.Cells(18, 5)
x = ActiveSheet.Cells(25, 1)
EoverD = ActiveSheet.Cells(1, 5)
Re = ActiveSheet.Cells(2, 5)
ActRow = 25
i = 0
While ((i <= iMax) And (Abs(xnew) > Tol))
i = i + 1
FofX = (-1 / Sqr(x)) - (2 * (Log((EoverD / 3.7) + (2.51 / (Re * Sqr(x)))) / Log(10)))
DfDx = Fcalc(x)
xnew = x - (FofX / DfDx)
x = xnew
ActiveSheet.Cells(25 + i, 1) = x
ActiveSheet.Cells(24 + i, 2) = FofX
ActiveSheet.Cells(24 + i, 3) = DfDx
ActiveSheet.Cells(24 + i, 4) = i
Wend
End Sub
Function Fcalc(x)
Fcalc = (1 / x^(1.5)) + ((2 / Log(10)) * ((2.51 / (2 * Re * x^(1.5))) / ((EoverD / 3.7) + (2.51 / Re * Sqr(x)))))
End Function
Iterations continue until xnew = 0 within a given tolerance
I wrote a code and my logic seems good to me. I can't find any issues. The program is not giving me any errors, but it will not output anything. I have my output inside the loop. I can't figure out what's wrong. Does anyone see why this is not outputting anything? Please and thank you!
I attached a screenshot of my spreadsheet so you can see how I have it set up.
Thanks so much.
Sub NewtonMethod()
Dim x As Double
Dim xnew As Double
Dim EoverD As Double
Dim Re As Double
Dim ActRow As Integer
Dim FofX As Double
Dim DfDx As Double
Dim Tol As Double
Dim iMax As Integer
Dim i As Integer
Worksheets(ActiveSheet.Name).Activate
iMax = 100
Tol = ActiveSheet.Cells(18, 5)
x = ActiveSheet.Cells(25, 1)
EoverD = ActiveSheet.Cells(1, 5)
Re = ActiveSheet.Cells(2, 5)
ActRow = 25
i = 0
While ((i <= iMax) And (Abs(xnew) > Tol))
i = i + 1
FofX = (-1 / Sqr(x)) - (2 * (Log((EoverD / 3.7) + (2.51 / (Re * Sqr(x)))) / Log(10)))
DfDx = Fcalc(x)
xnew = x - (FofX / DfDx)
x = xnew
ActiveSheet.Cells(25 + i, 1) = x
ActiveSheet.Cells(24 + i, 2) = FofX
ActiveSheet.Cells(24 + i, 3) = DfDx
ActiveSheet.Cells(24 + i, 4) = i
Wend
End Sub
Function Fcalc(x)
Fcalc = (1 / x^(1.5)) + ((2 / Log(10)) * ((2.51 / (2 * Re * x^(1.5))) / ((EoverD / 3.7) + (2.51 / Re * Sqr(x)))))
End Function