BookmarkSubscribeRSS Feed
ItsMeAG
Fluorite | Level 6

Hi Friends,

 

See the following code 

 

data tmp1;
a = 0.8;
b = 0.6;
c = 0.4;
d = 0.2;
total = sum(a,b,c,d);
run;
 
data tmp2;
set tmp1;
if total >= 2 then flag = 1;
else flag = 0;
diff = sum(-2,total);
format diff 32.25;
run;
 
print of tmp2:
ItsMeAG_0-1756413618933.png

 

Here I am getting total = 2 , but when it comes to if condition it's not satisfying '>= 2' and getting flag values as 0.
I tried to see the difference of total with 2, and getting "-0.00000000000000022204".
 
Can someone please help me to understand why the value of total  is not actually 2 and how to solve it.
 
Thanks in advance for your time and support!
2 REPLIES 2
Tom
Super User Tom
Super User

Because SAS (and most computer languages) use BINARY (base 2) floating point numbers.  Not the decimal numbers (base 10) that humans like to use.

 

None of those values can be exactly represented as binary numbers.  And when you add them all up the difference is enough that the normal equality test considers the values to be unequal.

 

Why not just the ROUND() function to reduce the number to a reasonable number of digits.

data test;
  input x1-x4;
  total = sum(of x1-x4);
  diff = total-2;
  if total=2 then put TOTAL= 'is exactly 2.';
  if round(total,0.0001)=2 then put TOTAl= 'is close enough to 2.'
    / 'since difference is ' diff:32.25 
  ;
cards;
.8 .6 .4 .2
;
Patrick
Opal | Level 21

In the SAS docu under Numeric Precision some more detail for what @Tom already explained.

hackathon24-white-horiz.png

Join the 2025 SAS Hackathon!

Calling all data scientists and open-source enthusiasts! Want to solve real problems that impact your company or the world? Register to hack by August 31st!

Register Now

How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 2 replies
  • 157 views
  • 0 likes
  • 3 in conversation