REXX Tips & Tricks, Version 2.80


Inf-HTML [About][Toc][Index] 0.9b (c) 1995 Peter Childs


Sqrt routine



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.  If           */
/* this routine is saved as RXSQRT.CMD, "RXSQRT 5" will               */
/* give square root of 5.  If you insert debug, for example           */
/* "RXSQRT DEBUG 5", you can watch the algorithm. The                 */
/* "/" at the start of the first line must be in col 1.               */
/*                                                                    */
/* 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




Inf-HTML End Run - Successful