Unintentional Loss of Precision

From sasCommunity
Jump to: navigation, search

Passing Floating Point Values as Macro Variables

Macro variables can be handy for passing scalar values from one step to another. However, when the values have many significant digits, there can be loss of precision.

Here's an example. First compute a ratio and store it in a macro variable:

proc sql noprint;
         create table demo (fraction1 num);
         insert into demo set fraction1 = 1 / 3;
         select fraction1 
         into : fraction2 
         from demo;
         quit;

Now compare the value extracted from the macro variable to the value passed in the data set:

data _null_;
set  demo;
fraction2 = &fraction2;
put (fraction : )( / = 16.14);
run;

Result:

fraction1=0.33333333333333
fraction2=0.33333300000000

The behavior is similar when a DATA step rather than SQL is used to create the data.

One solution is to pass the value expressed as a hexadecimal string. This will preserve the value exactly:

proc sql noprint;
         create table demo (fraction1 num);
insert into demo set fraction1 = 1 / 3;
select put(fraction1,hex16.) into : fraction2 from demo;
quit;
data _null_;

set demo;
fraction2 = input("&fraction2",hex16.);
put (fraction : )( / = best32.);
run;

Result:

fraction1=0.33333333333333
fraction2=0.33333333333333

Note that this approach cannot be used successfully if the value is being passed from one host platform to another.

See also Passing Real Numbers as Macro Variables

Other Scenarios Causing Unintentional Loss of Precision?