gpt4 book ai didi

c++ - Kahan求和算法用GCC编译时计算误差大

转载 作者:搜寻专家 更新时间:2023-10-31 02:16:05 26 4
gpt4 key购买 nike

我用的是Kahan求和算法:

inline void KahanSum(float value, float & sum, float & correction)
{
float term = value - correction;
float temp = sum + term;
correction = (temp - sum) - term;
sum = temp;
}

float KahanSum(const float * ptr, size_t size)
{
float sum = 0, correction = 0;
for(size_t i = 0; i < size; ++i)
KahanSum(ptr[i], sum, correction);
return sum;
}

如果用MSVS编译可以正常运行,但是用GCC的话会出现很大的计算错误。

问题出在哪里?

最佳答案

我想,这是积极的编译器优化的结果。所以 GCC 可以减少来自的表达式:

    float term = value - correction;
float temp = sum + term;
correction = (temp - sum) - term;
sum = temp;

    float term = value - correction;
correction = 0;
sum += term;

因为这个变换在数学上是正确的,但是这个优化杀死了卡汉算法。

为了避免这个问题,您可以使用“-O1”GCC 编译器选项来编译代码。它将是这样的:

#if defined(__GNUC__)
# pragma GCC push_options
# pragma GCC optimize ("O1")
#endif
inline void KahanSum(float value, float & sum, float & correction)
{
float term = value - correction;
float temp = sum + term;
correction = (temp - sum) - term;
sum = temp;
}

float KahanSum(const float * ptr, size_t size)
{
float sum = 0, correction = 0;
for(size_t i = 0; i < size; ++i)
KahanSum(ptr[i], sum, correction);
return sum;
}
#if defined(__GNUC__)
# pragma GCC pop_options
#endif

关于c++ - Kahan求和算法用GCC编译时计算误差大,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37486225/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com