float_equal.hpp 1.13 KB
Newer Older
Paul's avatar
Paul committed
1
2
#ifndef MIGRAPH_GUARD_MIGRAPHLIB_FLOAT_EQUAL_HPP
#define MIGRAPH_GUARD_MIGRAPHLIB_FLOAT_EQUAL_HPP
Paul's avatar
Paul committed
3
4
5
6
7
8
9
10

#include <algorithm>
#include <cmath>
#include <numeric>
#ifdef _MSC_VER
#include <iso646.h>
#endif

Paul's avatar
Paul committed
11
#include <migraph/requires.hpp>
12
#include <migraph/config.hpp>
Paul's avatar
Paul committed
13

14
namespace migraph { inline namespace MIGRAPH_INLINE_NS {
Paul's avatar
Paul committed
15
16
17
18
19
20

template <class... Ts>
using common_type = typename std::common_type<Ts...>::type;

struct float_equal_fn
{
Paul's avatar
Paul committed
21
    template <class T, MIGRAPH_REQUIRES(std::is_floating_point<T>{})>
Paul's avatar
Paul committed
22
23
24
25
26
27
28
    static bool apply(T x, T y)
    {
        return std::isfinite(x) and std::isfinite(y) and
               std::nextafter(x, std::numeric_limits<T>::lowest()) <= y and
               std::nextafter(x, std::numeric_limits<T>::max()) >= y;
    }

Paul's avatar
Paul committed
29
30
31
32
33
34
    template <class T, MIGRAPH_REQUIRES(not std::is_floating_point<T>{})>
    static bool apply(T x, T y)
    {
        return x == y;
    }

Paul's avatar
Paul committed
35
36
37
38
39
40
41
42
43
    template <class T, class U>
    bool operator()(T x, U y) const
    {
        return float_equal_fn::apply<common_type<T, U>>(x, y);
    }
};

static constexpr float_equal_fn float_equal{};

44
} // inline namespace MIGRAPH_INLINE_NS
Paul's avatar
Paul committed
45
} // namespace migraph
Paul's avatar
Paul committed
46
47

#endif