Sample 24618: Determine the nth root of a positive or negative variable
Use macro logic to determine the nth root of a value even
if the value is negative.
The macro has three parameters:
INVAR contains the value whose nth root is to be determined
OUTVAR contains the nth root = INVAR**(1/ROOT)
ROOT contains the root to take.
For example, if you want to take the cube root, set ROOT
equal to 3.
%macro nroot(invar,outvar,root);
/* If the root is odd, then take the root of the absolute value and */
/* multiply by the sign of the original value */
if mod(&root,2)=1 then &outvar=sign(&invar)*abs(&invar)**(1/&root);
else do;
/* If the root is even and the original value is negative then */
/* assign a missing value */
if &invar<0 then &outvar=.;
/* Otherwise just take the root */
else &outvar=&invar**(1/&root);
end;
%mend nroot;
/* Use the macro */
data test;
/* Generate some data */
do i=1 to 10;
x=rannor(123);
y=x**3;
/* Take the square root of y and store in y2root */
%nroot(y,y2root,2);
/* Take the cube root of y and store in y3root */
%nroot(y,y3root,3);
output;
end;
run;
proc print data=test;
run;
Obs i x y y2root y3root
1 1 -0.32659 -0.03484 . -0.32659
2 2 1.54244 3.66963 1.91563 1.54244
3 3 0.25903 0.01738 0.13183 0.25903
4 4 -0.55583 -0.17173 . -0.55583
5 5 0.77872 0.47222 0.68718 0.77872
6 6 -0.65520 -0.28127 . -0.65520
7 7 -0.02210 -0.00001 . -0.02210
8 8 -0.77265 -0.46126 . -0.77265
9 9 0.72423 0.37987 0.61634 0.72423
10 10 1.26331 2.01620 1.41993 1.26331
Use macro logic to determine the nth root of a value even
if the value is negative.
| Type: | Sample |
| Topic: | SAS Reference ==> DATA Step SAS Reference ==> Functions ==> Mathematical
|
| Date Modified: | 2005-12-16 03:02:54 |
| Date Created: | 2004-09-30 14:08:58 |
Operating System and Release Information
| SAS System | Base SAS | All | n/a | n/a |