gpt4 book ai didi

c++ - 这种与浮点文字零的比较有效吗?

转载 作者:太空宇宙 更新时间:2023-11-04 13:34:55 27 4
gpt4 key购买 nike

来自 N3337(C++11 草案)第 3.9.1.8 节:

The value representation of floating-point types is implementation-defined.

这是否适用于浮点类型的任何和所有用法,无论它是否为文字?这是引起我一些担忧的示例:

float foo{0.0f};
if (foo == 0.0f)
{
// Am I always guaranteed to get here?
}

如果我们假设 0.0f 就实现而言不是真正的 0,而是一些未定义的数字,这种比较在技术上是否仍然有效,因为两个操作数都是通过常量获得的,甚至虽然我可能不知道它的真正值(value),但它们仍然是一样的吗?

像这样与浮点文字的相等比较总是有代码味道,我只是想确保在某些用例中这没有意义或有效。

最佳答案

是的,您一定会到达那里。对相关数字进行处理操作后出现 float 不精确。常量在您的情况下是安全的。

但是,如果您通过提供过多的小数来超出 float 精度,或者您使用其他数据类型初始化 float ,则可能会得到不同的解释。

例如,这可能不会成功:

float foo{2.1234321f};
if (foo * 6.1234321f / 0.1234321f == 105.3428750f)
{
// Am I always guaranteed to get here? Not at all.
}

如果你想在比较 float 时是安全的,你应该“近似”结果。请参阅下面的代码。

#include <limits>
#include <type_traits>

using namespace std;

class exact{};
class approx{};

template<class> struct tolerance;

template<>
struct tolerance<float>
{
static constexpr float value() { return 0.00001; }
}

template<class T>
bool close_enough(T a, T b, exact)
{
return a == b;
}

template<class T>
bool close_enough(T a, T b, approx)
{
return abs(a - b) <= tolerance<T>::value();
}

template<class T>
bool close_enough(T a, T b)
{
return close_enough(a, b,
conditional<numeric_limits<T>::is_exact, exact, approx>::type{});
}

int main()
{
float a = 2.1234321f, b = 105.3428750f;

if (close_enough(a * 6.1234321f / 0.1234321f, b))
{
// Am I always guaranteed to get here? Yes!
}
else
{
// ...
}
}

关于c++ - 这种与浮点文字零的比较有效吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29904728/

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