Odd behavior with SAS numeric comparison; precision issue?

纵然是瞬间 提交于 2021-01-28 11:36:38

问题


I'm running a simple inequality filter in SAS as follows:

data my_data;
    set my_data;
    my_var = sum(parent_var1, -parent_var2)
run;

proc sql;
    select my_var format=32.32
    from my_data
    where my_var < 0.02;
quit;

I get the following result:

my_var
.0200000000000000000000000000000
.0200000000000000000000000000000
.0200000000000000000000000000000
(etc...)

The problem, in case it's not obvious, is that I want numbers below .02, but it looks very much like my number is .02.

According to the properties listed when I view my dataset, the length of my_var is set to 8. parent_var1 and parent_var2 are both decimal numbers, length 8 and format 8.5.

Can someone explain what might be going on here? Is there some hidden precision somewhere that I'm not able to see?


回答1:


SAS only has floating point binary data type for numbers. There is no type that does decimal arithmetic instead. So you might have a value that is slightly less than 0.02.

You might want to round your values to some fixed number of decimal places, say four or five. Try this code on your data and check if you still see those 0.02 value.

data my_data;
   set my_data;
   my_var = round(sum(parent_var1, -parent_var2),0.00001) ;
   if my_var < 0.02 then put (my_var paren_var1 parent_var2) (= best32.8) ;
run;



回答2:


You could try to use the FUZZ function which returns the nearest integer if the argument is close enough. However, you would need to multiply both sides of the where expression by 100 to make it work properly.

proc sql;
    select my_var format=32.32
    from my_data
    where fuzz(my_var * 100) < 2;
quit;

More information on why this happens with float point types you could find in the following papers/presentations:

  • DH08: Do Not Trust Your Own Computer generated Numbers - PHUSE EU Connect 2019 - Matthias Lehrkamp, also slides
  • https://0.30000000000000004.com/


来源:https://stackoverflow.com/questions/59743802/odd-behavior-with-sas-numeric-comparison-precision-issue

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!