sin_pi.hpp 2.3 KB

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