cos_pi.hpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // Copyright (c) 2007 John Maddock
  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_COS_PI_HPP
  6. #define BOOST_MATH_COS_PI_HPP
  7. #ifdef _MSC_VER
  8. #pragma once
  9. #endif
  10. #include <boost/math/special_functions/math_fwd.hpp>
  11. #include <boost/config/no_tr1/cmath.hpp>
  12. #include <boost/math/tools/config.hpp>
  13. #include <boost/math/special_functions/trunc.hpp>
  14. #include <boost/math/tools/promotion.hpp>
  15. #include <boost/math/constants/constants.hpp>
  16. namespace boost{ namespace math{ namespace detail{
  17. template <class T, class Policy>
  18. T cos_pi_imp(T x, const Policy& pol)
  19. {
  20. BOOST_MATH_STD_USING // ADL of std names
  21. // cos of pi*x:
  22. bool invert = false;
  23. if(fabs(x) < 0.25)
  24. return cos(constants::pi<T>() * x);
  25. if(x < 0)
  26. {
  27. x = -x;
  28. }
  29. T rem = floor(x);
  30. if(iconvert(rem, pol) & 1)
  31. invert = !invert;
  32. rem = x - rem;
  33. if(rem > 0.5f)
  34. {
  35. rem = 1 - rem;
  36. invert = !invert;
  37. }
  38. if(rem == 0.5f)
  39. return 0;
  40. if(rem > 0.25f)
  41. {
  42. rem = 0.5f - rem;
  43. rem = sin(constants::pi<T>() * rem);
  44. }
  45. else
  46. rem = cos(constants::pi<T>() * rem);
  47. return invert ? T(-rem) : rem;
  48. }
  49. } // namespace detail
  50. template <class T, class Policy>
  51. inline typename tools::promote_args<T>::type cos_pi(T x, const Policy&)
  52. {
  53. typedef typename tools::promote_args<T>::type result_type;
  54. typedef typename policies::evaluation<result_type, Policy>::type value_type;
  55. typedef typename policies::normalise<
  56. Policy,
  57. policies::promote_float<false>,
  58. policies::promote_double<false>,
  59. policies::discrete_quantile<>,
  60. policies::assert_undefined<>,
  61. // We want to igore overflows since the result is in [-1,1] and the
  62. // check slows the code down considerably.
  63. policies::overflow_error<policies::ignore_error> >::type forwarding_policy;
  64. return policies::checked_narrowing_cast<result_type, forwarding_policy>(boost::math::detail::cos_pi_imp<value_type>(x, forwarding_policy()), "cos_pi");
  65. }
  66. template <class T>
  67. inline typename tools::promote_args<T>::type cos_pi(T x)
  68. {
  69. return boost::math::cos_pi(x, policies::policy<>());
  70. }
  71. } // namespace math
  72. } // namespace boost
  73. #endif