-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalc_util.h
49 lines (38 loc) · 1.12 KB
/
calc_util.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#pragma once
#ifndef CALC_UTIL_H
#define CALC_UTIL_H
#include <limits>
#include <type_traits>
#include <string>
#include <cmath>
namespace tpcalc {
// almost_equal:
template <typename T>
typename std::enable_if_t<std::is_floating_point_v<T>, bool> almost_equal(T x, T y, unsigned ulp = 1)
// see https://en.cppreference.com/w/cpp/types/numeric_limits/epsilon
{
// the machine epsilon has to be scaled to the magnitude of the values used
// and multiplied by the desired precision in ULPs (units in the last place)
return std::fabs(x-y) <= std::numeric_limits<T>::epsilon() * std::fabs(x+y) * ulp
// unless the result is subnormal
|| std::fabs(x-y) < std::numeric_limits<T>::min();
}
// resetter, make_resetter:
template <typename T>
struct resetter {
T& var;
T value;
resetter(T& var_, const T& value_)
: var(var_), value(value_) {}
~resetter() {var = value;}
};
template <typename T>
resetter<T> make_resetter(T& var, const T& value) {
return resetter<T>(var, value);
}
// internal_error:
struct internal_error {
std::string str;
};
} // namespace tpcalc
#endif // CALC_UTIL_H