相同的浮点运算,结果不同

时间:2013-08-06 08:20:08

标签: c++ floating-point ieee-754

我真的无法理解这个代码给出了相同公式的2个结果:

#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);
}

我真的不认为IEEE 754浮点表示在这里发挥了重要作用......

2 个答案:

答案 0 :(得分:3)

第一个表达式(即(exp(M_PI) - M_PI))是double,第二个表达式(即a)是float。即使具有 20个十进制数字的精度,但float的精度要低于double

答案 1 :(得分:2)

由于M_PI的类型为double,因此将a更改为double,您将获得相同的结果:

#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);
}