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)
6 #include <boost/test/unit_test.hpp>
7 #include <boost/test/floating_point_comparison.hpp>
8 #include <boost/random.hpp>
9 #include <boost/range/iterator_range.hpp>
10 #include <boost/accumulators/accumulators.hpp>
11 #include <boost/accumulators/statistics/stats.hpp>
12 #include <boost/accumulators/statistics/weighted_median.hpp>
14 using namespace boost
;
15 using namespace unit_test
;
16 using namespace accumulators
;
18 ///////////////////////////////////////////////////////////////////////////////
23 // Median estimation of normal distribution N(1,1) using samples from a narrow normal distribution N(1,0.01)
24 // The weights equal to the likelihood ratio of the corresponding samples
26 // two random number generators
28 double sigma_narrow
= 0.01;
30 boost::lagged_fibonacci607 rng
;
31 boost::normal_distribution
<> mean_sigma_narrow(mu
,sigma_narrow
);
32 boost::variate_generator
<boost::lagged_fibonacci607
&, boost::normal_distribution
<> > normal_narrow(rng
, mean_sigma_narrow
);
34 accumulator_set
<double, stats
<tag::weighted_median(with_p_square_quantile
) >, double > acc
;
35 accumulator_set
<double, stats
<tag::weighted_median(with_density
) >, double >
36 acc_dens( density_cache_size
= 10000, density_num_bins
= 1000 );
37 accumulator_set
<double, stats
<tag::weighted_median(with_p_square_cumulative_distribution
) >, double >
38 acc_cdist( p_square_cumulative_distribution_num_cells
= 100 );
41 for (std::size_t i
=0; i
<100000; ++i
)
43 double sample
= normal_narrow();
44 acc(sample
, weight
= std::exp(0.5 * (sample
- mu
) * (sample
- mu
) * ( 1./sigma_narrow
/sigma_narrow
- 1./sigma
/sigma
)));
45 acc_dens(sample
, weight
= std::exp(0.5 * (sample
- mu
) * (sample
- mu
) * ( 1./sigma_narrow
/sigma_narrow
- 1./sigma
/sigma
)));
46 acc_cdist(sample
, weight
= std::exp(0.5 * (sample
- mu
) * (sample
- mu
) * ( 1./sigma_narrow
/sigma_narrow
- 1./sigma
/sigma
)));
49 BOOST_CHECK_CLOSE(1., weighted_median(acc
), 2);
50 BOOST_CHECK_CLOSE(1., weighted_median(acc_dens
), 3);
51 BOOST_CHECK_CLOSE(1., weighted_median(acc_cdist
), 3);
54 ///////////////////////////////////////////////////////////////////////////////
55 // init_unit_test_suite
57 test_suite
* init_unit_test_suite( int argc
, char* argv
[] )
59 test_suite
*test
= BOOST_TEST_SUITE("weighted_median test");
61 test
->add(BOOST_TEST_CASE(&test_stat
));