|
|
Title | Use Newton's method to find the roots of an equation in Visual Basic 6 |
Description | This example shows how to use Newton's method to find the roots of an equation in Visual Basic 6. |
Keywords | Newton's method, equation, root, zero |
Categories | Algorithms, Graphics |
|
|
Newton's method calculates the roots of equations. In other words, it finds
the values of X for which F(X) = 0.
This program graphs the equation X^3/3 - 2*X + 5. When you click on the
graph, it uses Newton's method to find a root of the equation, starting from
the X value that you clicked.
|
|
' The function.
Private Function F(ByVal X As Double) As Single
F = X * X * X / 3 - 2 * X * X + 5
End Function
' Draw the background graph.
Private Sub DrawGraph()
Const STEP_SIZE As Single = 0.1
Dim X As Single
Dim Y As Single
Dim y1 As Single
Dim y2 As Single
Me.Cls
' Draw the axes.
For X = -10 To 10
Me.Line (X, -0.5)-Step(0, 1), vbBlue
Next X
For Y = -10 To 10
Me.Line (-0.5, Y)-Step(1, 0), vbBlue
Next Y
Me.Line (-10, 0)-Step(20, 0), vbBlue
Me.Line (0, -10)-Step(0, 20), vbBlue
' Draw the curve.
y2 = F(-10)
For X = -10 + STEP_SIZE To 10 Step STEP_SIZE
y1 = y2
y2 = F(X)
Me.Line (X - STEP_SIZE, y1)-(X, y2), vbRed
Next X
End Sub
|
|
The way Newton's method works is it starts from an initial guess X0 (given
by the point you clicked). It then estimates the difference between that
value and root:
epsilon = -F(x) / dFdx(x)
The method then sets its next guess for x to be the current value plus
epsilon (X(n+1) = X(n) + epsilon). It repeats this process until epsilon is
smaller than some cutoff value.
|
|
' The function's derivative.
Private Function dFdx(ByVal X As Double) As Single
dFdx = X * X - 4 * X
End Function
' Find the roots by using Newton's method.
Private Sub Form_MouseDown(Button As Integer, Shift As _
Integer, X As Single,
Y As Single)
Const CUTOFF As Single = 0.0000001
Dim epsilon As Single
Dim iterations As Integer
Dim x0 As Single
' Clear previous results.
DrawGraph
x0 = X
iterations = 0
Do
iterations = iterations + 1
Me.Line (x0, -1.5)-Step(0, 3)
epsilon = -F(x0) / dFdx(x0)
x0 = x0 + epsilon
Loop While Abs(epsilon) > CUTOFF
Me.Line (x0, -3)-Step(0, 6)
Me.Caption = x0 & " +/-" & epsilon & " in " & _
iterations & " iterations"
End Sub
|
|
Newton's method uses the function's derivative to make its next X value
guess. If the curve is relatively flat for the current value of X, then the
derivative (which is the slope of the function) gives a value far away from
the current one and the method is unstable. In this example, try clicking on
a point where X is at or near 0 and see what happens.
For more information on Newton's method, see Eric W. Weisstein's article
Newton's Method from MathWorld--A Wolfram Web Resource.
|
|
|
|
|
|