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

别来无恙 提交于 2019-12-06 04:04:32

This is only a guess, you would need to look at the assembly output from the compiler to know for sure.

It is possible that one compiler left intermediate results in a floating-point register while the other wrote the results to memory, rounding it from 80 bits to 64. It's also possible that one uses SSE and the other does not.

Because you are doing an equality comparison on floating-point types, which in general should not be relied upon for particular bit-exact behaviour from machine to machine (or from compiler to compiler, etc.).

Possible reasons include the compiler's choice of when to move floating-point results out of wide (80-bit) floating-point registers (neither the language standard nor the IEEE-754 floating-point standard impose any particular requirements, AFAIK).

it is because of floating point arithmetic, try using epsilon comparisions instead:

#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!");

because it is not correct to compare floating point numbers like that due to precision problems.

In mathematics 2/3= (0.6666666..... to infinity)//primary school math :) no questions asked.

In computing this calculation is carried out on the floating point unit (similar to CPU but is dedicated for floating point calculations). Now this floating point unit (FPU) may give you a number very close to your actual answer but they are not exactly the same. because it will truncate the results. There is an entire field dedicated to floating point arithmetic. In short never use floating point numbers in comparisons because you may get conflicting results.

Shahbaz

Testing for equality between floating point numbers is problematic. This is because of rounding errors and there are many, MANY texts on this on the internet.

You can see this here, here, here, here, here and basically any result in a google search for floating point equality.

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