【问题标题】:constexpr: errors with floating point representation?constexpr:浮点表示错误?
【发布时间】:2013-12-26 21:13:03
【问题描述】:

我希望将常数从度数转换为弧度(在编译时),所以我选择使用 constexpr。但是,我的程序无法编译,因此我尝试通过一些测试来调试问题。这些测试在编译期间继续产生错误。

当涉及许多有效数字时,问题似乎与浮点运算相关。

我尝试了快速的谷歌搜索,并阅读了 Stroustrup 书中的第 10.4 节(常量表达式)。任何帮助将不胜感激。我一定遗漏了一些明显的东西。

测试代码:

void testConstantExpressions() {

  constexpr double x0 = 1.0;
  constexpr double y0 = 2.0;
  constexpr double z0 = 4.0;
  constexpr double w0 = x0 / (y0 / z0);
  std::cout << w0 << std::endl;

  constexpr double x1 = 1.0;
  constexpr double y1 = 2.2;
  constexpr double z1 = 4.0;
  constexpr double w1 = x1 / (y1 / z1);
  std::cout << w1 << std::endl;

  constexpr double x2 = 1.0;
  constexpr double y2 = 4.0;
  constexpr double z2 = 2.3;
  constexpr double w2 = x2 / (y2 / z2);
  std::cout << w2 << std::endl;

}

编译器:

g++ -Wall -c -g -O2 -std=c++11 -frounding-math  main.cpp -o main.o
main.cpp: In function ‘void testConstantExpressions()’:
main.cpp:30:32: error: ‘(1.0e+0 / 5.5000000000000004e-1)’ is not a constant expression
   constexpr double w1 = x1 / (y1 / z1);
                            ^
main.cpp:36:38: error: ‘(4.0e+0 / 2.2999999999999998e+0)’ is not a constant expression
   constexpr double w2 = x2 / (y2 / z2);
                                  ^
make: *** [main.o] Error 1

【问题讨论】:

  • 在这里用 g++ 编译得很好
  • 我在这里没有看到任何无理数。
  • GCC 在使用-frounding-math 时有一些限制。请参阅 this bugthis other one。另外,this.
  • @Kyle 哎呀,我在为这篇文章选择标题后更改了我的示例。
  • 挑剔:没有无理数可以用double 表示。

标签: c++ c++11 constexpr


【解决方案1】:

这是因为您指定了 -frounding-math。您告诉编译器您可能会在运行时更改舍入模式,因此它不能在编译时进行舍入。你真的是故意的吗?

【讨论】:

  • 我的理解是 -frounding-math 是使用 Computational Geometry Algorithms Library (我的项目使用)所必需的。无论如何我可以将 constexpr 与 -frounding-math 一起使用吗?
  • 也许您可以将需要修改舍入模式的位分离出来,让大部分程序以更正常的方式编译?
猜你喜欢
  • 2011-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-15
  • 1970-01-01
相关资源
最近更新 更多