Sqrt routine

[Autolink] Menu

SQRT-Routine from Bob Price (see EMail Addresses)
Captured from a message in a public CompuServe Forum

 
/* ------------------------------------------------------------------ */
/* REXX exec to calculate a square root using an optimized            */
/* version of the ever-popular Newton-Raphson method.                 */
/* Alter numeric digits for desired level of precision.               */
/*                                                                    */
/* Author: Bob Price                                                  */
/**********************************************************************/

  numeric digits 21

  do forever
    call CharOut, "Enter a number (RETURN to exit): "
    thisNumber = strip( lineIN() )

    select
      when thisNumber = "" then
        leave

      when datatype( thisNumber ) <> "NUM" then
        say "Invalid response!"

      when thisNumber <= 0 then
        say "Invalid number!"

      otherwise
      do
        thisSqrt = SQRT( thisNumber )
        Say " The Square root of " || thisNumber || " is " || thisSqrt
        Say " Controlvalue: "
        Say " " || thisSqrt "*" thisSqrt "=" thisSqrt*thisSqrt
      end /* otherwise */
    end /* select */
  end /* do forever */

exit 0

/* ------------------------------------------------------------------ */
/* function: calculate the square root of a number                    */
/*                                                                    */
/* call:     Sqrt number                                              */
/*                                                                    */
/* where:    number - number to calculate the square root of          */
/*                                                                    */
/* returns:  the square root                                          */
/*                                                                    */
SQRT: PROCEDURE
  ARG n
        /* ans, the "answer", will be brought to the square root by   */
        /* successive approximation.                                  */
  ans = n / 2                   /* initial guess at an answer         */
  prevans = n                   /* "previous answer"                  */
  do until prevans = ans        /* i.e., no more improvement is found */
     prevans = ans              /* save previous answer               */
     ans = ( prevans + ( n / prevans ) ) / 2
  end
return ans


[Back: SQRT routine]
[Next: Math. functions]