简体   繁体   English

constexpr:浮点表示错误?

[英]constexpr: errors with floating point representation?

I was hoping to convert a constant from degrees to radians (at compile time), so I opted to use a constexpr. 我希望将常量从度数转换为弧度(在编译时),所以我选择使用constexpr。 However, my program would not compile and so I tried to debug the problem with a few tests. 但是,我的程序不会编译,因此我尝试通过一些测试来调试问题。 These tests continue to produce errors during compilation. 这些测试在编译期间继续产生错误。

The problem appears to be correlated with floating point arithmetic when many significant digits are involved. 当涉及许多有效数字时,该问题似乎与浮点算法相关。

I tried a quick google search, and I read section 10.4 (Constant Expressions) in Stroustrup's book. 我尝试了一个快速的谷歌搜索,我在Stroustrup的书中阅读了10.4节(常量表达式)。 Any help would be greatly appreciated. 任何帮助将不胜感激。 I must be missing something obvious. 我一定错过了一些明显的东西。

Test code: 测试代码:

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;

}

Compiler: 编译:

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

It's because you specified -frounding-math. 这是因为你指定了-frounding-math。 You told the compiler you might change rounding mode at runtime, so it can't round at compile time. 您告诉编译器您可能在运行时更改舍入模式,因此它无法在编译时进行舍入。 Did you really mean to? 你真的有意义吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM