Solved
Contributor
Posts: 27

# Add 1, subtract 1

Hi,

why is it that these two codes work:

data strange;
variable = 1/5;
if variable = 0.2;
run;

data strange2;
variable = 1 - 1 +1/5;
if variable = 0.2;
run;

but this one doesn't:

data strange3;
variable = 1/5 + 1 - 1;
if variable = 0.2;
run;

?

thank you,
Marco

Accepted Solutions
Solution
‎03-18-2014 02:19 PM
Super User
Posts: 7,944

## Re: Add 1, subtract 1

Posted in reply to data_null__

1/5 cannot be exactly represented as a binary number.  The order of operations matter because by adding 1 to 1/5 you have moved where the first 1 is in the binary representation, thus leaving fewer bits to represent the value of 1/5.

All Replies
Posts: 3,847

## Re: Add 1, subtract 1

Posted in reply to Lupacante

I don't know why order of operations matters here but it does.  It's a floating point thing.

data _null_;
variable1 =
1/5;
variable2 =
1 - 1 +1/5;
variable3 =
1/5 + 1 - 1;

put (variable (=hex16. / );
run;

variable1=3FC999999999999A
variable2=3FC999999999999A
variable3=3FC9999999999998
Solution
‎03-18-2014 02:19 PM
Super User
Posts: 7,944

## Re: Add 1, subtract 1

Posted in reply to data_null__

1/5 cannot be exactly represented as a binary number.  The order of operations matter because by adding 1 to 1/5 you have moved where the first 1 is in the binary representation, thus leaving fewer bits to represent the value of 1/5.

Contributor
Posts: 27

## Re: Add 1, subtract 1

Thanks Tom, that's interesting.

Do you know how I might be able to rewrite the code to make it work regardless of the order or operations?

Thank you,

Marco

Posts: 3,847

## Re: Add 1, subtract 1

Posted in reply to Lupacante

Just round it.

data _null_;
v1 =
1/5;
v2 =
1 - 1 +1/5;
v3 =
1/5 + 1 - 1;
r1 = round(v1,
1e-6);
r2 = round(v2,1e-6);
r3 = round(v3,1e-6);
put (v: r (=hex16. / );
run;

v1=3FC999999999999A
v2=3FC999999999999A
v3=3FC9999999999998
r1=3FC999999999999A
r2=3FC999999999999A
r3=3FC999999999999A
PROC Star
Posts: 1,288

## Re: Add 1, subtract 1

Posted in reply to Lupacante

Approach this with caution. These comparisons are inherently wobbly in computing systems, and what works for one example may fail in another.

Why are you trying to make this equality comparison? There may be a way to do it that will avoid this difficulty.

Tom

Super User
Posts: 13,358

## Re: Add 1, subtract 1

Posted in reply to Lupacante

Note behavior for this as well which does yield expected results.

data strange4;
variable = 1/5 + (1 - 1);
if variable = 0.2;
run;

🔒 This topic is solved and locked.

Need further help from the community? Please ask a new question.

Discussion stats
• 6 replies
• 455 views
• 7 likes
• 5 in conversation