1 // (C) Copyright Nick Thompson 2019.
2 // Use, modification and distribution are subject to the
3 // Boost Software License, Version 1.0. (See accompanying file
4 // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6 #ifndef BOOST_MATH_TOOLS_CONDITION_NUMBERS_HPP
7 #define BOOST_MATH_TOOLS_CONDITION_NUMBERS_HPP
9 #include <boost/math/differentiation/finite_difference.hpp>
11 namespace boost::math::tools {
13 template<class Real, bool kahan=true>
14 class summation_condition_number {
16 summation_condition_number(Real const x = 0)
24 void operator+=(Real const & x)
27 // No need to Kahan the l1 calc; it's well conditioned:
42 inline void operator-=(Real const & x)
47 // Is operator*= relevant? Presumably everything gets rescaled,
48 // (m_sum -> k*m_sum, m_l1->k*m_l1, m_c->k*m_c),
49 // but is this sensible? More important is it useful?
50 // In addition, it might change the condition number.
52 [[nodiscard]] Real operator()() const
55 if (m_sum == Real(0) && m_l1 != Real(0))
57 return std::numeric_limits<Real>::infinity();
59 return m_l1/abs(m_sum);
62 [[nodiscard]] Real sum() const
64 // Higham, 1993, "The Accuracy of Floating Point Summation":
65 // "In [17] and [18], Kahan describes a variation of compensated summation in which the final sum is also corrected
66 // thus s=s+e is appended to the algorithm above)."
70 [[nodiscard]] Real l1_norm() const
81 template<class F, class Real>
82 Real evaluation_condition_number(F const & f, Real const & x)
87 using boost::math::differentiation::finite_difference_derivative;
92 return std::numeric_limits<Real>::quiet_NaN();
94 bool caught_exception = false;
98 fp = finite_difference_derivative(f, x);
102 caught_exception = true;
105 if (isnan(fp) || caught_exception)
107 // Check if the right derivative exists:
108 fp = finite_difference_derivative<decltype(f), Real, 1>(f, x);
111 // Check if a left derivative exists:
112 const Real eps = (std::numeric_limits<Real>::epsilon)();
113 Real h = - 2 * sqrt(eps);
114 h = boost::math::differentiation::detail::make_xph_representable(x, h);
121 return std::numeric_limits<Real>::quiet_NaN();
130 return std::numeric_limits<Real>::quiet_NaN();
132 return std::numeric_limits<Real>::infinity();