c++ - 如何重现浮点 cos(x)!=cos(x)

标签 c++ c floating-point-precision x87

如何重现此行为? https://isocpp.org/wiki/faq/newbie#floating-point-arith2

准确的说,在下面的代码中,参数xy是相等的;它们可以等于 1.0 或任何其他值。

void foo(double x, double y)
{
  double cos_x = cos(x);
  double cos_y = cos(y);
  // the behavior might depend on what's in here
  if (cos_x != cos_y) {
    std::cout << "Huh?!?\n";  // You might end up here when x == y!!
  }
}

一些编译器选项?环形?有什么想法吗?

最佳答案

我会尝试按照链接示例中的方式进行操作:不将结果存储到临时变量中。文章中提到,浮点运算通常是在位数比 RAM 多的寄存器中计算的。例如,如果只有一个浮点运算寄存器,那么在进行 cos 计算后,结果必须存储在 RAM 中以便进行其他 cos计算。来自文章:

Suppose your code computes cos(x), then truncates that result and stores it into a temporary variable, say tmp. It might then compute cos(y), and (drum roll please) compare the untruncated result of cos(y) with tmp, that is, with the truncated result of cos(x).

当您将两个结果都存储在变量中时(取决于优化等),第二次 cos 计算的结果很有可能也会在计算之前存储在 RAM 中。由于结果将以相同的方式截断,因此它们将作为 == 进行比较。

关于c++ - 如何重现浮点 cos(x)!=cos(x),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30786415/

相关文章:

python - 计算大型稀疏矩阵的迹

c - argv 数组的元素在内存中总是连续的吗?

C++ Qt 如何在滚动区域添加小部件?

C++ - 在同一程序中运行一个服务器线程和一个客户端线程

c - #C - 简单路径 - 有向图 - 递归

c++ - 用泰勒级数计算正弦值时出现的问题

objective-c - Objective-C 中的 float 问题

c++ - 在 C++ 中进行数学运算时,浮点错误如何传播?

c++ - 除以零预防 : Checking the divisor's expression doesn't result in zero vs. 检查除数不为零?

c++ - 从文件名变量中删除 ".txt"