Same C ++ "if" statement, different results on Linux / Windows

I found an interesting case when the same C ++ code gives different results on different systems.

#include <cstdio>
int main()
{
    int a=20, b=14;
    if(a*1.0/b*(a+1)/(b+1)==2) printf("YES!");
    else printf("NO!");
}

Compiled on Ubuntu Linux 12.04 using GCC 4.6.3 it outputs YES!

Compiled on Windows 7 using GCC 4.6.2 it outputs NO!

However, using:

double  c = a*1.0/b*(a+1)/(b+1);
if (c==2) printf("YES!");
...

will return YES! on both machines.

Any ideas why this difference comes up? Is this the reason for the compiler version mismatch (the path level version number should not matter WHAT)? And why does he really get NO! on a windows machine, although this condition is obviously true?

+3
source
5

, , , .

, , , 80 64. , SSE, .

+12

, ( ..).

, (80-) ( , IEEE-754 , AFAIK).

+14

- , epsilon:

#define EPSILON_EQUAL(a,b) ( fabs((a)-(b)) < (0.0001f) )

float f = a*1.0/b*(a+1)/(b+1);
if(EPSILON_EQUAL(f,2.0f)) printf("YES!");
+2

, - .

2/3 = (0.6666666..... )// :) .

( , ). (FPU) , , . . , . , .

+1

. - , .

You can see here here , here , here , here , here and basically any Google search result floating point equality.

0
source

All Articles