gpt4 book ai didi

c++ - cmath 精度误差中的底函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:51:08 28 4
gpt4 key购买 nike

所以我最近在尝试涉及浮点运算的问题。下面是该代码的一个片段。

#include<cstdio>
#include<cmath>
typedef unsigned long long ull;

int main(){
long double n=1000000000,ans,ans1,ans2;
ans = (n*n/48.0);

ans1 = std::floor(ans+0.5); // Correct, got AC with this
ans2 = floor(ans+0.5); // Incorrect, got me 2 WA :(

printf("%llu %llu\n",ull(ans1),ull(ans2));
}

输出:

20833333333333333 20833333333333332

在这个问题中,我不得不四舍五入最后的答案。我首先使用了 cmath 的 round 函数,但得到了 WA。然后经过一番谷歌搜索后,我发现了这个很好的简单方法来舍入否

n = floor(n + 0.5);

但是让我吃惊的是 floor 函数的奇怪行为。它在与 std 命名空间一起使用时表现不同,实际上它只有在那时才能正确表现。

我的猜测是来自 std 命名空间的 floor 函数返回一个 long double,而来自 cmath 的正常 floor 函数返回一个 double ,因此精度损失。

所以我想知道为什么这两个函数在 cmath 中位于不同的命名空间中,如果编译器选择适当的 floor 函数不是更好吗,因为我向它传递了一个“long double”,就像正常的方法重载一样。

谢谢

最佳答案

cmath 中的 floor 函数是 C 的继承,在 C++ 提出 floorlong double 版本之前就已经存在了...现在我们不能删除它,因为它已经被使用了,所以新的是在 std 中创建的。

floor(ans+0.5) 会将 (ans + 0.5) 转换为“普通” double ,因此会损失精度。

关于c++ - cmath 精度误差中的底函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22131368/

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