1

can anyone help me why the results of two below calculations are different?

double a= 1e-14;
double b= 1e-7;
double val=0;
val+=b;
val-=(a/b);

which results something like -4.3.....e-24 for val.

double a= 1e-14;
double b= 1e-7;
double val=0;
val+=b;
double val2= a/b;
val-=val2;

which results 0 for val. Can anyone explain that to me?

I'm using math.h library with MinGW.

all
  • 85
  • 11
  • 1
    Different rounding different outcome: https://stackoverflow.com/q/588004/1387438 – Marek R Jul 01 '22 at 13:50
  • 1
    I can't reproduce. What compiler and OS? Are you building with `-ffast-math`? – HolyBlackCat Jul 01 '22 at 13:52
  • 1
    Cannot reproduce, the results are not even close to the one you are writing. https://godbolt.org/z/M4qjhd3Wz Both are `-1.32349e-23`. – mch Jul 01 '22 at 13:52
  • Printing both with `%.100e` gives exactly the same digits: https://godbolt.org/z/83esaWvas – mch Jul 01 '22 at 13:54
  • @HolyBlackCat I'm using math.h library with MinGW. – all Jul 01 '22 at 13:59
  • 1
    You're not using any library functions in this code. Which version of MinGW? (What site did you download it from?) There are plenty of different flavors. What compiler flags? No `-ffast-math` I hope? – HolyBlackCat Jul 01 '22 at 14:00
  • @HolyBlackCat I'm using only this option: -c -fmessage-length=0. the version i think is 4.8.2 and is installed using MinGW installer – all Jul 01 '22 at 14:13
  • 1
    Where did you download it from? In any case, I suggest replacing it with [MSYS2](https://stackoverflow.com/q/30069830/2752075) (since yours is horribly outdated, 4.8.2 vs 12.1). On which, by the way, I get the same answer from both snippets, regardless of `-ffast-math`. – HolyBlackCat Jul 01 '22 at 14:16

0 Answers0