使用std::vector中的std::complex<double>为何出现机器精度级差异?
std::complex 在-O3优化下调用std::pow的精度差异问题
- 调试单元测试时发现:直接对临时构造的
std::complex<double>调用std::pow,与对std::vector中存储的std::complex<double>调用std::pow的结果,存在机器精度(约1.11022e-16)级的差异,该现象仅在-O3编译优化下出现。 - 复现环境:AMD EPYC 7713 64核处理器,GCC 11.2.0、12.1.0版本均可复现。
- 无差异情况:使用float、double或
std::complex<float>时未发现该精度差异。
测试代码
#include <complex> #include <iostream> #include <vector> int main(int argc, const char * argv[]) { std::vector<std::complex<double>> base(1, 4.0); std::vector<std::complex<double>> exp(1, -0.23); std::cout << std::pow(std::complex(4.0), std::complex(-0.23)) - std::pow(base.at(0), exp.at(0)) << std::endl; return 0; }
GCC 11.2.0编译运行结果
perlmutter:~/bug> /opt/cray/pe/gcc/11.2.0/bin/c++ --version c++ (GCC) 11.2.0 20210728 (Cray Inc.) Copyright (C) 2021 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. perlmutter:~/bug> /opt/cray/pe/gcc/11.2.0/bin/c++ -O3 -o test test.cpp perlmutter:~/bug> ./test (1.11022e-16,-0)
GCC 12.1.0编译运行结果
(base) perlmutter:~/bug> gcc --version gcc (GCC) 12.1.0 20220506 (HPE) Copyright (C) 2022 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. perlmutter:~/bug> g++ -O3 -o test test.cpp perlmutter:~/bug> ./test (1.11022e-16,-0)
内容的提问来源于stack exchange,提问作者user1139069
相关产品推荐
相关产品推荐

