weighted_median.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // (C) Copyright 2006 Eric Niebler, Olivier Gygi
  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. #include <boost/test/unit_test.hpp>
  6. #include <boost/test/floating_point_comparison.hpp>
  7. #include <boost/random.hpp>
  8. #include <boost/range/iterator_range.hpp>
  9. #include <boost/accumulators/accumulators.hpp>
  10. #include <boost/accumulators/statistics/stats.hpp>
  11. #include <boost/accumulators/statistics/weighted_median.hpp>
  12. using namespace boost;
  13. using namespace unit_test;
  14. using namespace accumulators;
  15. ///////////////////////////////////////////////////////////////////////////////
  16. // test_stat
  17. //
  18. void test_stat()
  19. {
  20. // Median estimation of normal distribution N(1,1) using samples from a narrow normal distribution N(1,0.01)
  21. // The weights equal to the likelihood ratio of the corresponding samples
  22. // two random number generators
  23. double mu = 1.;
  24. double sigma_narrow = 0.01;
  25. double sigma = 1.;
  26. boost::lagged_fibonacci607 rng;
  27. boost::normal_distribution<> mean_sigma_narrow(mu,sigma_narrow);
  28. boost::variate_generator<boost::lagged_fibonacci607&, boost::normal_distribution<> > normal_narrow(rng, mean_sigma_narrow);
  29. accumulator_set<double, stats<tag::weighted_median(with_p_square_quantile) >, double > acc;
  30. accumulator_set<double, stats<tag::weighted_median(with_density) >, double >
  31. acc_dens( density_cache_size = 10000, density_num_bins = 1000 );
  32. accumulator_set<double, stats<tag::weighted_median(with_p_square_cumulative_distribution) >, double >
  33. acc_cdist( p_square_cumulative_distribution_num_cells = 100 );
  34. for (std::size_t i=0; i<1000000; ++i)
  35. {
  36. double sample = normal_narrow();
  37. double w = std::exp(
  38. 0.5 * (sample - mu) * (sample - mu) * (
  39. 1./sigma_narrow/sigma_narrow - 1./sigma/sigma
  40. )
  41. );
  42. acc(sample, weight = w);
  43. acc_dens(sample, weight = w);
  44. acc_cdist(sample, weight = w);
  45. }
  46. BOOST_CHECK_CLOSE(1., weighted_median(acc), 2);
  47. BOOST_CHECK_CLOSE(1., weighted_median(acc_dens), 3);
  48. BOOST_CHECK_CLOSE(1., weighted_median(acc_cdist), 3);
  49. }
  50. ///////////////////////////////////////////////////////////////////////////////
  51. // init_unit_test_suite
  52. //
  53. test_suite* init_unit_test_suite( int argc, char* argv[] )
  54. {
  55. test_suite *test = BOOST_TEST_SUITE("weighted_median test");
  56. test->add(BOOST_TEST_CASE(&test_stat));
  57. return test;
  58. }