integrate.hpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /* integrate.hpp header file
  2. *
  3. * Copyright Jens Maurer 2000
  4. * Distributed under the Boost Software License, Version 1.0. (See
  5. * accompanying file LICENSE_1_0.txt or copy at
  6. * http://www.boost.org/LICENSE_1_0.txt)
  7. *
  8. * $Id$
  9. *
  10. * Revision history
  11. * 01 April 2001: Modified to use new <boost/limits.hpp> header. (JMaddock)
  12. */
  13. #ifndef INTEGRATE_HPP
  14. #define INTEGRATE_HPP
  15. #include <boost/limits.hpp>
  16. template<class UnaryFunction>
  17. inline typename UnaryFunction::result_type
  18. trapezoid(UnaryFunction f, typename UnaryFunction::argument_type a,
  19. typename UnaryFunction::argument_type b, int n)
  20. {
  21. typename UnaryFunction::result_type tmp = 0;
  22. for(int i = 1; i <= n-1; ++i)
  23. tmp += f(a+(b-a)/n*i);
  24. return (b-a)/2/n * (f(a) + f(b) + 2*tmp);
  25. }
  26. template<class UnaryFunction>
  27. inline typename UnaryFunction::result_type
  28. simpson(UnaryFunction f, typename UnaryFunction::argument_type a,
  29. typename UnaryFunction::argument_type b, int n)
  30. {
  31. typename UnaryFunction::result_type tmp1 = 0;
  32. for(int i = 1; i <= n-1; ++i)
  33. tmp1 += f(a+(b-a)/n*i);
  34. typename UnaryFunction::result_type tmp2 = 0;
  35. for(int i = 1; i <= n ; ++i)
  36. tmp2 += f(a+(b-a)/2/n*(2*i-1));
  37. return (b-a)/6/n * (f(a) + f(b) + 2*tmp1 + 4*tmp2);
  38. }
  39. // compute b so that f(b) = y; assume f is monotone increasing
  40. template<class UnaryFunction, class T>
  41. inline T
  42. invert_monotone_inc(UnaryFunction f, typename UnaryFunction::result_type y,
  43. T lower = -1,
  44. T upper = 1)
  45. {
  46. while(upper-lower > 1e-6) {
  47. double middle = (upper+lower)/2;
  48. if(f(middle) > y)
  49. upper = middle;
  50. else
  51. lower = middle;
  52. }
  53. return (upper+lower)/2;
  54. }
  55. // compute b so that I(f(x), a, b) == y
  56. template<class UnaryFunction>
  57. inline typename UnaryFunction::argument_type
  58. quantil(UnaryFunction f, typename UnaryFunction::argument_type a,
  59. typename UnaryFunction::result_type y,
  60. typename UnaryFunction::argument_type step)
  61. {
  62. typedef typename UnaryFunction::result_type result_type;
  63. if(y >= 1.0)
  64. return std::numeric_limits<result_type>::infinity();
  65. typename UnaryFunction::argument_type b = a;
  66. for(result_type result = 0; result < y; b += step)
  67. result += step*f(b);
  68. return b;
  69. }
  70. #endif /* INTEGRATE_HPP */