hypot.hpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // (C) Copyright John Maddock 2005-2006.
  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)
  5. #ifndef BOOST_MATH_HYPOT_INCLUDED
  6. #define BOOST_MATH_HYPOT_INCLUDED
  7. #ifdef _MSC_VER
  8. #pragma once
  9. #endif
  10. #include <boost/math/tools/config.hpp>
  11. #include <boost/math/tools/precision.hpp>
  12. #include <boost/math/policies/error_handling.hpp>
  13. #include <boost/math/special_functions/math_fwd.hpp>
  14. #include <algorithm> // for swap
  15. #include <cmath>
  16. namespace boost{ namespace math{ namespace detail{
  17. template <class T, class Policy>
  18. T hypot_imp(T x, T y, const Policy& pol)
  19. {
  20. //
  21. // Normalize x and y, so that both are positive and x >= y:
  22. //
  23. using std::fabs; using std::sqrt; // ADL of std names
  24. x = fabs(x);
  25. y = fabs(y);
  26. #ifdef _MSC_VER
  27. #pragma warning(push)
  28. #pragma warning(disable: 4127)
  29. #endif
  30. // special case, see C99 Annex F:
  31. if(std::numeric_limits<T>::has_infinity
  32. && ((x == std::numeric_limits<T>::infinity())
  33. || (y == std::numeric_limits<T>::infinity())))
  34. return policies::raise_overflow_error<T>("boost::math::hypot<%1%>(%1%,%1%)", nullptr, pol);
  35. #ifdef _MSC_VER
  36. #pragma warning(pop)
  37. #endif
  38. if(y > x)
  39. (std::swap)(x, y);
  40. if(x * tools::epsilon<T>() >= y)
  41. return x;
  42. T rat = y / x;
  43. return x * sqrt(1 + rat*rat);
  44. } // template <class T> T hypot(T x, T y)
  45. }
  46. template <class T1, class T2>
  47. inline typename tools::promote_args<T1, T2>::type
  48. hypot(T1 x, T2 y)
  49. {
  50. typedef typename tools::promote_args<T1, T2>::type result_type;
  51. return detail::hypot_imp(
  52. static_cast<result_type>(x), static_cast<result_type>(y), policies::policy<>());
  53. }
  54. template <class T1, class T2, class Policy>
  55. inline typename tools::promote_args<T1, T2>::type
  56. hypot(T1 x, T2 y, const Policy& pol)
  57. {
  58. typedef typename tools::promote_args<T1, T2>::type result_type;
  59. return detail::hypot_imp(
  60. static_cast<result_type>(x), static_cast<result_type>(y), pol);
  61. }
  62. } // namespace math
  63. } // namespace boost
  64. #endif // BOOST_MATH_HYPOT_INCLUDED