MeVisLab Toolbox Reference
mlNumericHelpers.h
Go to the documentation of this file.
1/*************************************************************************************
2**
3** Copyright 2020, MeVis Medical Solutions AG
4**
5** The user may use this file in accordance with the license agreement provided with
6** the Software or, alternatively, in accordance with the terms contained in a
7** written agreement between the user and MeVis Medical Solutions AG.
8**
9** For further information use the contact form at https://www.mevislab.de/contact
10**
11**************************************************************************************/
12
13#ifndef ML_NUMERIC_HELPERS_H
14#define ML_NUMERIC_HELPERS_H
15
16#include <algorithm>
17#include <limits>
18#include <cmath>
19
20namespace ml
21{
22 /*
23 * Convert a character sequence to a corresponding integral value
24 */
25 template <typename T, std::size_t N> constexpr T convertTo(const char (&t)[N])
26 {
27 static_assert(N - 1 == sizeof(T), "Illegal character sequence for type T");
28 T result{};
29 for (auto index = 0u; index < N - 1; ++index)
30 result = (result << 8) + t[index];
31 return result;
32 }
33
34
35 /*
36 * Helper function that checks if two floating point values are equal in within a certain epsilon
37 * \param x The first value
38 * \param y The second value
39 * \param absoluteEpsilon If both values are close to zero, this epsilon is taken
40 * \param relativeEpsilon If both values are not close to zero this relative epsilon is used
41 */
42 template <typename T>
43 constexpr bool almostEqualRelativeAndAbs(T x, T y, T absoluteEpsilon, T relativeEpsilon = std::numeric_limits<T>::epsilon())
44 {
45 static_assert(std::is_floating_point_v<T>, "Deduced type T should be a floating point type");
46
47 // When the values are close to zero, then the relative epsilon does not work.
48 auto diff = std::fabs(x - y);
49 if (diff <= absoluteEpsilon)
50 return true;
51
52 x = std::fabs(x);
53 y = std::fabs(y);
54 T largest = std::max(x, y);
55
57 return true;
58
59 return false;
60 }
61
62
63
64}
65
66#endif // MEVISLAB_MLNUMERICHELPERS_H
@ T
@ N
Target mlrange_cast(Source arg)
Generic version of checked ML casts.
Main documentation file for ML users and developers.
Definition SoSFMLImage.h:51
constexpr T convertTo(const char(&t)[N])
constexpr bool almostEqualRelativeAndAbs(T x, T y, T absoluteEpsilon, T relativeEpsilon=std::numeric_limits< T >::epsilon())