gpt4 book ai didi

c++ - 在比较 float 时使用 epsilon 是否会破坏严格弱排序?

转载 作者:行者123 更新时间:2023-12-04 12:13:55 26 4
gpt4 key购买 nike

以下类(class)是否打破了严格的弱排序(与常规 std::less 相比(因此忽略边缘情况值,例如 Nan))

struct LessWithEpsilon
{
static constexpr double epsilon = some_value;
bool operator() (double lhs, double rhs) const
{
return lhs + epsilon < rhs;
}
};

LessWithEpsilon lessEps{};

最佳答案

来自 https://en.wikipedia.org/wiki/Weak_ordering#Strict_weak_orderings

  1. Transitivity of incomparability: For all x,y,z in S, if x is incomparable with y (meaning that neither x < y nor y < x is true) and if y is incomparable with z, then x is incomparable with z.

同样,来自 https://en.cppreference.com/w/cpp/named_req/Compare

If equiv(a, b) == true and equiv(b, c) == true, then equiv(a, c) == true


{x, y, z} = {0, epsilon, 2 * epsilon} ,该规则被打破:
  • !lessEps(x, y) && !lessEps(y, x) && !lessEps(y, z) && !lessEps(z, y)但是 lessEps(x, z) .
  • equiv(x, y) == true and equiv(y, z) == true但是 equiv(x, z) == false (如 x + epsilon < z)

  • 因此,该类打破了严格弱序。

    关于c++ - 在比较 float 时使用 epsilon 是否会破坏严格弱排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68114060/

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