float_equal.hpp 1.16 KB
Newer Older
Paul's avatar
Paul committed
1
2
#ifndef MIGRAPHX_GUARD_MIGRAPHLIB_FLOAT_EQUAL_HPP
#define MIGRAPHX_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
12
#include <migraphx/requires.hpp>
#include <migraphx/config.hpp>
13
#include <migraphx/type_traits.hpp>
Paul's avatar
Paul committed
14

Paul's avatar
Paul committed
15
namespace migraphx {
Paul's avatar
Paul committed
16
inline namespace MIGRAPHX_INLINE_NS {
Paul's avatar
Paul committed
17
18
19
20
21
22

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

struct float_equal_fn
{
23
    template <class T, MIGRAPHX_REQUIRES(is_floating_point<T>{})>
Paul's avatar
Paul committed
24
25
26
27
28
29
30
    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;
    }

31
    template <class T, MIGRAPHX_REQUIRES(not is_floating_point<T>{})>
Paul's avatar
Paul committed
32
33
34
35
36
    static bool apply(T x, T y)
    {
        return x == y;
    }

Paul's avatar
Paul committed
37
38
39
40
41
42
43
44
45
    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{};

Paul's avatar
Paul committed
46
} // namespace MIGRAPHX_INLINE_NS
Paul's avatar
Paul committed
47
} // namespace migraphx
Paul's avatar
Paul committed
48
49

#endif