True BASIC Program to Find Root

by Namir Shammas

The following program calculates the root of a function using Newton's algorithm:

x' = x - f(x) / f '(x)

where f(x) is the function whose root is sought. f '(x) is the first derivative of function f(x). The program approximate the derivative using:

f '(x) = (f(x + h) - f(x)) / h

where h = 0.01 * (1 + |x|)

The program prompts you to enter a guess for the root. The program uses internally defined values of 1e-8 and 55 for the tolerance and maximum iterations, respectively.

The program displays the following results:

1. The root value.

2. The number of iterations.

If the number of iterations exceeds the maximum limit, the program displays the text SOLUTION FAILED before displaying the above results.

Here is the BASIC listing:

OPTION TYPO
OPTION NOLET

! Find root of nonlinear function using Newton's method

! User function
DEF Fx(X) = EXP(X) - 3 * X^2

Declare Numeric Tolerance, X, h, F, Diff, Iter, MaxIter

Tolerance = 1e-8
MaxIter = 55

CLEAR
PRINT "NEWTON'S METHOD TO SOLVE FOR THE ROOT OF A NONLINEAR EQUATION"
PRINT

INPUT PROMPT "Enter guess for root: ": X

Iter = 0
Do
  Iter = Iter + 1
  If Iter > MaxIter Then Exit Do
  h = 0.01 * (1 + ABS(X))
  F = Fx(X)
  Diff = h * F / (Fx(x+h) - F)
  X = X - Diff
Loop While Abs(Diff) > Tolerance

If Iter > MaxIter Then PRINT "SOLUTION DIVERGED!"
PRINT "Root = ";X
PRINT "Iterations = ";Iter

END

You can customize the above listing by changing the definition of function Fx. The current listing is set to solve the following equation:

f(x) = e^x - 3 * x^ 2

The above equation has roots near -0.45, 0.91, and 3.73.

You can also change the tolerance for the root by assigning a different value to the variable Tolerance. You can also change the maximum number of iterations by assigning a different value to the variable MaxIter.

BACK

Copyright (c) Namir Shammas. All rights reserved.