logit.hpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright Matt Borland 2025.
  2. // Use, modification and distribution are subject to the
  3. // Boost Software License, Version 1.0.
  4. // (See accompanying file LICENSE_1_0.txt
  5. // or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. #ifndef BOOST_MATH_SF_LOGIT_HPP
  7. #define BOOST_MATH_SF_LOGIT_HPP
  8. #include <boost/math/tools/config.hpp>
  9. #include <boost/math/policies/policy.hpp>
  10. #include <boost/math/policies/error_handling.hpp>
  11. #include <cmath>
  12. #include <cfenv>
  13. namespace boost {
  14. namespace math {
  15. template <typename RealType, typename Policy>
  16. RealType logit(RealType p, const Policy&)
  17. {
  18. BOOST_MATH_STD_USING
  19. using std::atanh;
  20. using promoted_real_type = typename policies::evaluation<RealType, Policy>::type;
  21. if (p < tools::min_value<RealType>())
  22. {
  23. return -policies::raise_overflow_error<RealType>("logit", "sub-normals will overflow ln(x/(1-x))", Policy());
  24. }
  25. static const RealType crossover {RealType{1}/4};
  26. const auto promoted_p {static_cast<promoted_real_type>(p)};
  27. RealType result {};
  28. if (p > crossover)
  29. {
  30. result = static_cast<RealType>(2 * atanh(2 * promoted_p - 1));
  31. }
  32. else
  33. {
  34. result = static_cast<RealType>(log(promoted_p / (1 - promoted_p)));
  35. }
  36. return result;
  37. }
  38. template <typename RealType>
  39. RealType logit(RealType p)
  40. {
  41. return logit(p, policies::policy<>());
  42. }
  43. } // namespace math
  44. } // namespace boost
  45. #endif // BOOST_MATH_SF_LOGIT_HPP