BornAgain  1.19.0
Simulate and fit neutron and x-ray scattering at grazing incidence
Numeric.cpp
Go to the documentation of this file.
1 // ************************************************************************************************
2 //
3 // BornAgain: simulate and fit reflection and scattering
4 //
5 //! @file Base/Math/Numeric.cpp
6 //! @brief Implements "almost equal" in namespace Numeric.
7 //!
8 //! @homepage http://www.bornagainproject.org
9 //! @license GNU General Public License v3 or higher (see COPYING)
10 //! @copyright Forschungszentrum Jülich GmbH 2018
11 //! @authors Scientific Computing Group at MLZ (see CITATION, AUTHORS)
12 //
13 // ************************************************************************************************
14 
15 #include "Base/Math/Numeric.h"
16 #include <algorithm>
17 #include <cmath>
18 #include <limits>
19 
20 namespace Numeric {
21 
22 //! Returns the absolute value of the difference between a and b.
23 double GetAbsoluteDifference(double a, double b)
24 {
25  return std::abs(a - b);
26 }
27 
28 //! Returns the safe relative difference, which is 2(|a-b|)/(|a|+|b|) except in special cases.
29 double GetRelativeDifference(double a, double b)
30 {
31  constexpr double eps = std::numeric_limits<double>::epsilon();
32  const double avg_abs = (std::abs(a) + std::abs(b)) / 2.0;
33  // return 0.0 if relative error smaller than epsilon
34  if (std::abs(a - b) <= eps * avg_abs)
35  return 0.0;
36  return std::abs(a - b) / avg_abs;
37 }
38 
39 //! Returns the difference of the logarithm; input values are truncated at the minimum positive
40 //! value
41 double GetLogDifference(double a, double b)
42 {
43  double a_t = std::max(a, std::numeric_limits<double>::min());
44  double b_t = std::max(b, std::numeric_limits<double>::min());
45  return std::abs(std::log(a_t) - std::log(b_t));
46 }
47 
48 } // namespace Numeric
Defines constants and "almost equal" in namespace Numeric.
Floating-point approximations.
Definition: Numeric.cpp:20
double GetRelativeDifference(double a, double b)
Returns the safe relative difference, which is 2(|a-b|)/(|a|+|b|) except in special cases.
Definition: Numeric.cpp:29
double GetAbsoluteDifference(double a, double b)
Returns the absolute value of the difference between a and b.
Definition: Numeric.cpp:23
double GetLogDifference(double a, double b)
Returns the difference of the logarithm; input values are truncated at the minimum positive value.
Definition: Numeric.cpp:41