This section presents a simple introductory SAS/IML program that implements a numerical algorithm that estimates the square root of a number, accurate to three decimal places. The following statements define a function module named MySqrt that performs the calculations:
proc iml; /* begin IML session */
start MySqrt(x); /* begin module */
y = 1; /* initialize y */
do until(w<1e-3); /* begin DO loop */
z = y; /* set z=y */
y = 0.5#(z+x/z); /* estimate square root */
w = abs(y-z); /* compute change in estimate */
end; /* end DO loop */
return(y); /* return approximation */
finish; /* end module */
You can call the MySqrt module to estimate the square root of several numbers given in a matrix literal (enclosed in braces) and print the results:
t = MySqrt({3,4,7,9}); /* call function MySqrt */
s = sqrt({3,4,7,9}); /* compare with true values */
diff = t - s; /* compute differences */
print t s diff; /* print matrices */
Figure 2.1: Approximate Square Roots