求一个数的平方根,各种程序都会有sqrt函数,SAS当然也有。本人不才,今天在SAS文档中查其他资料时,偶然发现这样一个求解平方根的算法。
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 */
print x y z ;
end; /* end DO loop */
return(y); /* return approximation */
finish;
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 */
部分输出结果:
xyz
31.73205081.7320508
422.0000001
72.64575132.645767
933.0000916
tsdiff
1.73205081.73205080
222.22E-15
2.64575132.64575134.678E-11
331.397E-9