gpt4 book ai didi

c++ - 除以非零值仍然可以创建一个南/无穷大

转载 作者:可可西里 更新时间:2023-11-01 16:28:05 30 4
gpt4 key购买 nike

我有一个可能为零的数字。我除以那个数字所以我想测试它是否为零以防止 NaN 和无穷大。由于除法中的舍入误差,我是否仍可能创建 NaN/无穷大?

double x; // might be zero
double y;

if(x != 0) return y / x;

编辑

感谢您的回复。然后我会添加一些子问题。

1) 假设 x 和 y 都不是 NaN/+inf 或 -inf,导致 -inf/+inf 的除法会导致更多 CPU 周期或任何其他不需要的行为吗? (它会崩溃吗?)

2) 有没有办法防止除法产生无穷大?使用偏移量等。

最佳答案

Can division by non-zero still create a nan / infinity

是的。

如果遵循 IEEE-754,则:

  • 如果任一操作数为 NaN,则结果将为 NaN。
  • 如果分子和分母均为无穷大,则结果为 NaN。
  • 如果只有分子为无穷大,则结果为无穷大。
  • 如果除以小分子(或大分子)溢出,结果可能是无穷大,具体取决于当前的舍入模式。

其他表示的规则可能不同。


2) is there a way to prevent the devision from resulting in infinity

这应该在很大程度上防止这种情况发生:

#include <cfenv>
#include <cassert>
#include <cmath>
#include <limits>

// ...

static_assert(std::numeric_limits<decltype(x)>::is_iec559, "Unknown floating point standard.");
#pragma STDC FENV_ACCESS ON
int failed = std::fesetround(FE_TOWARDZERO);
assert(!failed);
if(x != 0 && std::isfinite(x) && std::isfinite(y))
return y / x;
else
throw std::invalid_argument("informative message");

一些编译器可能需要非默认选项来启用完全 IEEE 754 合规性(GCC 上的 -frounding-math)。

关于c++ - 除以非零值仍然可以创建一个南/无穷大,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38571860/

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