0

When I want to compare two floating points values. I get strange results.

My example compiled with x86_64-w64-mingw32-g++ test.c -mfpmath=387:

#include "math.h"
#include "stdio.h"
int main(int argc, char **args) {

    double t1 = atof("999990") * 1e-9;
    double t2 = atof("999990") * 1e-9;
    printf("1) Compare of two variables \"t1 != t2\": ");
    if (t1 != t2) {
        printf("Not Equal\n");
    }
    else {
        printf("Equal\n");  //This is taken
    }
    printf("2) Compare of Variable with calculated value \"t1 != atof(\"999990\") * 1e-9\": ");
    if (t1 != atof("999990") * 1e-9) {
        printf("Not Equal\n");  //This is taken
    }
    else {
        printf("Equal\n");
    }
    printf("3) Compare of Variable with casted calculated value \"t1 != (double)(atof(\"999990\") * 1e-9)\": ");
    if (t1 != (double)(atof("999990") * 1e-9)) {
        printf("Not Equal\n");  //This is taken??
    }
    else {
        printf("Equal\n");
    }
    return 0;
}

First comparison: OK

Second comparison: OK (assuming right term is a 80Bit precision)

Why evaluates the third comparison to unequal? Why is the cast to double not recognised? Why is the result of the comparison different than the first case?

powerpete
  • 2,663
  • 2
  • 23
  • 49
  • 2
    You never should compare `float` or `double` values directly using the `==` operator. Internal representations might be different and aren't precise as you assume. – πάντα ῥεῖ Aug 31 '16 at 14:38
  • which hardware supports 80-bit precision? Even extended precision on Intel has only 64 bits of precision – phuclv Sep 01 '16 at 09:19
  • Compiling with -mfpmath=387 will use 387 Floating Point. Register size are 80 bit. [See this Entry](http://stackoverflow.com/a/3219838/2718002). Without this option SSE Unit is used. (64Bit) – powerpete Sep 01 '16 at 12:50

0 Answers0