I am writing a numerical analysis program, and i am working on Bisection method. I am writing it in VB because I am pretty comfortable with it. However, I cannot seem to figure out how to bring in a text string that contains the function at hand and then manipulate it so I can use the bisection method to figure the root. Below is my code so far. I would appreciate any help.
Option Explicit
Dim Tolerance As Double
Dim a As Double
Dim b As Double
Dim Max As Double
Dim root As Double
Dim funct As String
Dim x As Double
Dim p As Double
Dim i As Integer
Dim z As Integer
Dim f As Double
Dim result_a As Double
Dim result_p As Double
Dim result As Double
Dim newfunct As String
Dim val_funct As Double
Public Sub cmdRoot_Click()
funct = txtFunction.Text
a = txtEndA.Text
b = txtEndB.Text
Tolerance = txtTOL.Text
Max = Int(txtIterations.Text)
i = 1
result_a = eval(a, funct)
Do While i <= Max
p = a + ((b - a) / 2)
result_p = eval(p, funct)
If result_p = 0 Then
lblMessage.Caption = "Procedure completed successfully. The root is at x = " & Str(p)
Exit Do
End If
If ((b - a) / 2) < Tolerance Then
lblMessage.Caption = "Procedure completed successfully. The root is at x = " & Str(p)
Exit Do
End If
i = i + 1
If (result_a * result_p) > 0 Then
a = p
result_a = result_p
Else
b = p
End If
Loop
End Sub
Private Function eval(ByVal f As Double, ByRef funct As String) As Double
newfunct = Empty
For z = 1 To Len(funct)
If Mid(funct, z, 1) = "x" Then
newfunct = newfunct & Trim(Str(f))
Else
newfunct = newfunct & Mid(funct, z, 1)
End If
Next z
val_funct = Val(newfunct)
End Function
Note that this has been edited from original form to include suggestions.
Option Explicit
Dim Tolerance As Double
Dim a As Double
Dim b As Double
Dim Max As Double
Dim root As Double
Dim funct As String
Dim x As Double
Dim p As Double
Dim i As Integer
Dim z As Integer
Dim f As Double
Dim result_a As Double
Dim result_p As Double
Dim result As Double
Dim newfunct As String
Dim val_funct As Double
Public Sub cmdRoot_Click()
funct = txtFunction.Text
a = txtEndA.Text
b = txtEndB.Text
Tolerance = txtTOL.Text
Max = Int(txtIterations.Text)
i = 1
result_a = eval(a, funct)
Do While i <= Max
p = a + ((b - a) / 2)
result_p = eval(p, funct)
If result_p = 0 Then
lblMessage.Caption = "Procedure completed successfully. The root is at x = " & Str(p)
Exit Do
End If
If ((b - a) / 2) < Tolerance Then
lblMessage.Caption = "Procedure completed successfully. The root is at x = " & Str(p)
Exit Do
End If
i = i + 1
If (result_a * result_p) > 0 Then
a = p
result_a = result_p
Else
b = p
End If
Loop
End Sub
Private Function eval(ByVal f As Double, ByRef funct As String) As Double
newfunct = Empty
For z = 1 To Len(funct)
If Mid(funct, z, 1) = "x" Then
newfunct = newfunct & Trim(Str(f))
Else
newfunct = newfunct & Mid(funct, z, 1)
End If
Next z
val_funct = Val(newfunct)
End Function
Note that this has been edited from original form to include suggestions.
