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