bessel_zeros_interator_example.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // Copyright Christopher Kormanyos 2013.
  2. // Copyright Paul A. Bristow 2013.
  3. // Copyright John Maddock 2013.
  4. // Distributed under the Boost Software License, Version 1.0.
  5. // (See accompanying file LICENSE_1_0.txt or
  6. // copy at http://www.boost.org/LICENSE_1_0.txt).
  7. #ifdef _MSC_VER
  8. # pragma warning (disable : 4512) // assignment operator could not be generated.
  9. # pragma warning (disable : 4996) // assignment operator could not be generated.
  10. #endif
  11. #include <iostream>
  12. #include <limits>
  13. #include <vector>
  14. #include <algorithm>
  15. #include <iomanip>
  16. #include <iterator>
  17. //[bessel_zeros_iterator_example_1
  18. /*`[h5 Using Output Iterator to sum zeros of Bessel Functions]
  19. This example demonstrates summing zeros of the Bessel functions.
  20. To use the functions for finding zeros of the functions we need
  21. */
  22. #include <boost/math/special_functions/bessel.hpp>
  23. /*`We use the `cyl_bessel_j_zero` output iterator parameter `out_it`
  24. to create a sum of ['1/zeros[super 2]] by defining a custom output iterator:
  25. */
  26. template <class T>
  27. struct output_summation_iterator
  28. {
  29. output_summation_iterator(T* p) : p_sum(p)
  30. {}
  31. output_summation_iterator& operator*()
  32. { return *this; }
  33. output_summation_iterator& operator++()
  34. { return *this; }
  35. output_summation_iterator& operator++(int)
  36. { return *this; }
  37. output_summation_iterator& operator = (T const& val)
  38. {
  39. *p_sum += 1./ (val * val); // Summing 1/zero^2.
  40. return *this;
  41. }
  42. private:
  43. T* p_sum;
  44. };
  45. //] [/bessel_zeros_iterator_example_1]
  46. int main()
  47. {
  48. try
  49. {
  50. //[bessel_zeros_iterator_example_2
  51. /*`The sum is calculated for many values, converging on the analytical exact value of `1/8`.
  52. */
  53. using boost::math::cyl_bessel_j_zero;
  54. double nu = 1.;
  55. double sum = 0;
  56. output_summation_iterator<double> it(&sum); // sum of 1/zeros^2
  57. cyl_bessel_j_zero(nu, 1, 10000, it);
  58. double s = 1/(4 * (nu + 1)); // 0.125 = 1/8 is exact analytical solution.
  59. std::cout << std::setprecision(6) << "nu = " << nu << ", sum = " << sum
  60. << ", exact = " << s << std::endl;
  61. // nu = 1.00000, sum = 0.124990, exact = 0.125000
  62. //] [/bessel_zeros_iterator_example_2]
  63. }
  64. catch (std::exception const& ex)
  65. {
  66. std::cout << "Thrown exception " << ex.what() << std::endl;
  67. }
  68. return 0;
  69. } // int_main()
  70. /*
  71. Output:
  72. nu = 1, sum = 0.12499, exact = 0.125
  73. */