// Copyright John Maddock 2008. // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_MATH_DISTIBUTIONS_DETAIL_GENERIC_QUANTILE_HPP #define BOOST_MATH_DISTIBUTIONS_DETAIL_GENERIC_QUANTILE_HPP namespace boost{ namespace math{ namespace detail{ template struct generic_quantile_finder { using value_type = typename Dist::value_type; using policy_type = typename Dist::policy_type; generic_quantile_finder(const Dist& d, value_type t, bool c) : dist(d), target(t), comp(c) {} value_type operator()(const value_type& x) { return comp ? value_type(target - cdf(complement(dist, x))) : value_type(cdf(dist, x) - target); } private: Dist dist; value_type target; bool comp; }; template inline T check_range_result(const T& x, const Policy& pol, const char* function) { if((x >= 0) && (x < tools::min_value())) { return policies::raise_underflow_error(function, nullptr, pol); } if(x <= -tools::max_value()) { return -policies::raise_overflow_error(function, nullptr, pol); } if(x >= tools::max_value()) { return policies::raise_overflow_error(function, nullptr, pol); } return x; } template typename Dist::value_type generic_quantile(const Dist& dist, const typename Dist::value_type& p, const typename Dist::value_type& guess, bool comp, const char* function) { using value_type = typename Dist::value_type; using policy_type = typename Dist::policy_type; using forwarding_policy = typename policies::normalise< policy_type, policies::promote_float, policies::promote_double, policies::discrete_quantile<>, policies::assert_undefined<> >::type; // // Special cases first: // if(p == 0) { return comp ? check_range_result(range(dist).second, forwarding_policy(), function) : check_range_result(range(dist).first, forwarding_policy(), function); } if(p == 1) { return !comp ? check_range_result(range(dist).second, forwarding_policy(), function) : check_range_result(range(dist).first, forwarding_policy(), function); } generic_quantile_finder f(dist, p, comp); tools::eps_tolerance tol(policies::digits() - 3); std::uintmax_t max_iter = policies::get_max_root_iterations(); std::pair ir = tools::bracket_and_solve_root( f, guess, value_type(2), true, tol, max_iter, forwarding_policy()); value_type result = ir.first + (ir.second - ir.first) / 2; if(max_iter >= policies::get_max_root_iterations()) { return policies::raise_evaluation_error(function, "Unable to locate solution in a reasonable time:" // LCOV_EXCL_LINE " either there is no answer to quantile or the answer is infinite. Current best guess is %1%", result, forwarding_policy()); // LCOV_EXCL_LINE } return result; } }}} // namespaces #endif // BOOST_MATH_DISTIBUTIONS_DETAIL_GENERIC_QUANTILE_HPP