You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 00:20:32