hypot.hpp 2.2 KB

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