5

I am doing a x86 cross compile using gcc 8.3.0 with -ffast-math enabled of the following code:

#include <cmath>

double diff_double(double in)
{
  auto tmp = 10 * std::log10(1. * 15e3);
  return tmp - (10 * std::log10(1. * in));
}

int main()
{
    return diff_double(15e3) == 0.;
}

On execution, I get a return value of 0 because the compiler optimized result for "tmp" differs from the runtime result.

Is this a valid behavior?

Godbold: https://godbolt.org/z/g2sev7

Thanks for your help

Thomas m
  • 133
  • 4
  • 1
    *I get a return value of 0 because the compiler optimized result for "tmp" differs from the runtime result* -- I would have thought that you received a `0` due to floating-point inaccuracies. – PaulMcKenzie Nov 13 '19 at 13:42
  • GCC does all the calculations at compile time: https://godbolt.org/z/Ymg26N. Even without `-ffast-math`, the outcome is the very same. – Daniel Langr Nov 13 '19 at 13:45
  • 3
    For the not so math-savvy among us, what would be your **expected** return value from `diff_double`, and what is your **observed** return value from the function? Just so we're on the same page. – DevSolar Nov 13 '19 at 13:47
  • 1
    The dupe is very generic and I'm not sure it really applies. In any case: Yes, this is valid behavior, mainly because the C++ standard places almost no requirements on the floating point implementation. This excellent article covers this (heading "Transcendentals") and many other pains regarding practical floating point math and its (lack of) guarantees: https://randomascii.wordpress.com/2013/07/16/floating-point-determinism/ – Max Langhof Nov 13 '19 at 14:03
  • Added a godbolt example. -ffast-math does not make a difference, cross compile make the difference. Godbold: https://godbolt.org/z/g2sev7 – Thomas m Nov 14 '19 at 07:51

0 Answers0