Square root of positive real numbers

ALGORITHM
The square root of a positive real number N can be computed with Newton's formula:

New=0.5*(X+N/X)

where X above starts with a "reasonable" guess, e.g. (1+N)/2. It computes the square root until the absolute value of difference of two adjacent guess values is less than the tolerance value. Newton's iteration algorithm converges quadratically to the root.

IMPLEMENTATION
Unit: internal function, external function without procedure statement
 
Parameters: a positive real number N>0, a positive integer P - number of significant digits of SQRT(N), default is 9
 
Returns: the first P significant digits of SQRT(N)
 

SQRT: procedure parse arg N, P
if P = "" then P = 9; numeric digits P
parse value FORMAT(N,,,,0) with N "E" Exp
if Exp = "" then Exp = 0
if (Exp // 2) <> 0 then
  if Exp > 0
    then do; N = N * 10; Exp = Exp - 1; end
    else do; N = N / 10; Exp = Exp + 1; end
X = 0.5 * (N + 1)
do forever
  NewX = 0.5 * (X + N / X)
  if X = NewX then return X * 10 ** (Exp % 2)
  X = NewX
end

 

EXAMPLE
The following program

say SQRT(2)
say SQRT(2, 18)
exit
SQRT: procedure
...

displays on the screen

1.41421356
1.41421356237309505

 

CONNECTIONS


Cover Contents Index Main page

last modified 30th July 2001
Copyright 2000-2001 Vladimir Zabrodsky
Czech Republic