Search code examples
c++loggingfloor

different values of std::floor function for arguments with same value but different types


Consider the following:

#include <iostream>
#include <cmath>
int main()
{
  using std::cout;
  using std::endl;

  const long double be2 = std::log(2);
  cout << std::log(8.0) / be2 << ", " << std::floor(std::log(8.0) / be2)
      << endl;

  cout << std::log(8.0L) / be2 << ", " << std::floor(std::log(8.0L) / be2)
      << endl;
}

Outputs

  3, 2
  3, 3

Why does the output differ? What am I missing here?

Also here is the link to codepad: http://codepad.org/baLtYrmy

And I'm using gcc 4.5 on linux, if that's important.


Solution

  • When I add this:

    cout.precision(40);
    

    I get this output:

    2.999999999999999839754918906642444653698, 2
    3.00000000000000010039712117215771058909, 3
    

    You're printing two values that are very close to, but not exactly equal to, 3.0. It's the nature of std::floor that its results can differ for values that are very close together (mathematically, it's a discontinuous function).