float_equal.hpp 1.12 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
15
namespace migraph {
inline namespace MIGRAPH_INLINE_NS {
Paul's avatar
Paul committed
16
17
18
19
20
21

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

struct float_equal_fn
{
Paul's avatar
Paul committed
22
    template <class T, MIGRAPH_REQUIRES(std::is_floating_point<T>{})>
Paul's avatar
Paul committed
23
24
25
26
27
28
29
    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
30
31
32
33
34
35
    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
36
37
38
39
40
41
42
43
44
    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{};

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

#endif