GeneClaude 0 Newbie Poster

Hello! I've been debugging this VBA program that computes the root of an equation using Newton Raphson method and with the use of the UserForm. The user will type the equation, the initial guess and the number of iterations. I was able to search on automatically differentiating the equation unlike when the user still has to type in the derivation of the equation.

The next problem I encountered was the exponential function. I would like the program to evaluate the equation whether it is simple polynomial or exponential function. I'd like my program to be flexible in either of the two functions.

Here is the code for the computation part. All of these are contained in a module:

Function FxdPt(ByVal ig As Double, ByVal Equation As String, ByVal Iteration As Double) As Variant
    Dim xi As Double
    Dim iter As Integer
    Dim ea As Double

    Range("c20:c22").ClearContents
    Range("g9:k50").ClearContents

    On Error GoTo Handler


        iter = 1
        Do

            Sheets("Bracketing").Cells(21, 3) = iter
            Sheets("Bracketing").Cells(8 + iter, 7) = iter



            xi = ig - (f(Equation, ig) / diff(Equation, ig))

            Sheets("Bracketing").Cells(8 + iter, 9) = ig
            Sheets("Bracketing").Cells(8 + iter, 10) = xi
            iter = iter + 1

            ea = Abs((xi - ig) / xi)

            Sheets("Bracketing").Cells(7 + iter, 11) = ea

            If iter = Iteration + 1 Then
            Exit Do

            End If

            ig = xi

            DoEvents
        Loop
        FxdPt = xi
        Sheets("Bracketing").Cells(22, 3) = xi
        Sheets("Bracketing").Cells(20, 3) = ea

    Exit Function

Handler:
    FxdPt = "* Error / Overflow / Etcetera *"
End Function

Function diff(expression As String, variable As Double)
'Newton-Raphson Worksheet - Derivative calculation

deltah = 0.01
ex = Application.WorksheetFunction.Substitute(expression, "e", e)
diff = (Evaluate(Application.WorksheetFunction.Substitute(ex, "x", variable + deltah)) - _
            Evaluate(Application.WorksheetFunction.Substitute(ex, "x", variable))) / _
                (deltah)

End Function

Function f(expression As String, variable As Double)
Dim eqx As String


eqx = Application.WorksheetFunction.Substitute(expression, "e", e)
f = Application.WorksheetFunction.Substitute(eqx, "x", variable)

End Function

Tips/solutions would be a very great great help! I'm still new to VBA with not much introduction discussed in our course (Numerical Methods) so I hope you could help me. Thank you!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.