-1

I really can't wrap my head around the fact that this code gives 2 results for the same formula:

#include <iostream>
#include <cmath>

int main() {
  // std::cout.setf(std::ios::fixed, std::ios::floatfield);
  std::cout.precision(20);
  float a = (exp(M_PI) - M_PI);
  std::cout << (exp(M_PI) - M_PI) << "\n";
  std::cout << a << "\n";
  return (0);
}

I don't really think that the IEEE 754 floating point representation is playing a significant role here ...

user2485710
  • 9,451
  • 13
  • 58
  • 102

2 Answers2

3

The first expression (namely (exp(M_PI) - M_PI)) is a double, the second expression (namely a) is a float. Neither even have 20 decimal digits of precision, but the float has a lot less precision than the double.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
2

Because M_PI are of type double, so change a to double, you will have the same result:

#include <iostream>
#include <cmath>

int main() {
  // std::cout.setf(std::ios::fixed, std::ios::floatfield);
  std::cout.precision(20);
  double a = (exp(M_PI) - M_PI);
  std::cout << (exp(M_PI) - M_PI) << "\n";
  std::cout << a << "\n";
  return (0);
}
Yu Hao
  • 119,891
  • 44
  • 235
  • 294