std::floor函数的不同值用于具有相同值但不同类型的参数

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

本文关键字:同类型 参数 floor std 用于 函数      更新时间:2023-10-16

考虑以下内容:

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

输出

  3, 2
  3, 3

为什么输出不同?我在这里错过了什么?

这里还有代码板的链接:http://codepad.org/baLtYrmy

我在linux上使用gcc 4.5,如果这很重要的话。

当我添加这个时:

cout.precision(40);

我得到这个输出:

2.999999999999999839754918906642444653698, 2
3.00000000000000010039712117215771058909, 3

您打印的两个值非常接近,但并不完全等于3.0。std::floor的本质是,对于非常接近的值,其结果可能会有所不同(从数学上讲,它是一个不连续函数(。

#include <iostream>
#include <cmath>
#include <iomanip>
int main()
{
  using std::cout;
  using std::endl;
  const long double be2 = std::log(2);
  cout << setprecision (50)<<std::log(8.0)<<"n";
  cout << setprecision (50)<<std::log(8.0L)<<"n";
  cout << setprecision (50)<<std::log(8.0) / be2 << ", " << std::floor(std::log(8.0) / be2)
       << endl;
  cout << setprecision (50)<< std::log(8.0L) / be2 << ", " << std::floor(std::log(8.0L) / be2)
       << endl;
  return 0;
}

输出为:

2.0794415416798357476579894864698871970176696777344
2.0794415416798359282860714225549259026593063026667
2.9999999999999998397549189066424446536984760314226, 2
3.0000000000000001003971211721577105890901293605566, 3

如果您在此处检查输出,您会注意到两个输出的精度略有差异。这些舍入误差通常在float&在执行floor()时在这里加倍,并且出现的结果不是人们认为应该是的。

重要的是要记住两个属性Precision&使用浮点数或双位数时进行舍入

你可能想在我的回答中阅读更多关于它的信息,这里,同样的推理也适用于这里。

扩展Als所说的内容-

在第一种情况下,您将一个8字节的双精度值除以一个16字节长的双精度。在第二种情况下,您将16字节长的双精度除以16字节长双精度。这导致了一个非常小的舍入误差,可以在这里看到:

cout << std::setprecision(20) << (std::log(8.0) / be2) << std::endl;
cout << std::setprecision(20) << (std::log(8.0L) / be2) << std::endl;

产生:

2.9999999999999998398
3.0000000000000001004

编辑说:在这种情况下,sizeof是你的朋友(查看精度的差异(:

sizeof(std::log(8.0));  // 8
sizeof(std::log(8.0L)); // 16
sizeof(be2);            // 16