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 | |
6 | #include <boost/test/unit_test.hpp> |
7 | #include <boost/test/tools/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> |
13 | |
14 | using namespace boost; |
15 | using namespace unit_test; |
16 | using namespace accumulators; |
17 | |
18 | /////////////////////////////////////////////////////////////////////////////// |
19 | // test_stat |
20 | // |
21 | void test_stat() |
22 | { |
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 |
25 | |
26 | // two random number generators |
27 | double mu = 1.; |
28 | double sigma_narrow = 0.01; |
29 | double sigma = 1.; |
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); |
33 | |
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 ); |
39 | |
40 | |
41 | for (std::size_t i=0; i<1000000; ++i) |
42 | { |
43 | double sample = normal_narrow(); |
44 | double w = std::exp( |
45 | x: 0.5 * (sample - mu) * (sample - mu) * ( |
46 | 1./sigma_narrow/sigma_narrow - 1./sigma/sigma |
47 | ) |
48 | ); |
49 | acc(sample, weight = w); |
50 | acc_dens(sample, weight = w); |
51 | acc_cdist(sample, weight = w); |
52 | } |
53 | |
54 | BOOST_CHECK_CLOSE(1., weighted_median(acc), 2); |
55 | BOOST_CHECK_CLOSE(1., weighted_median(acc_dens), 3); |
56 | BOOST_CHECK_CLOSE(1., weighted_median(acc_cdist), 3); |
57 | } |
58 | |
59 | /////////////////////////////////////////////////////////////////////////////// |
60 | // init_unit_test_suite |
61 | // |
62 | test_suite* init_unit_test_suite( int argc, char* argv[] ) |
63 | { |
64 | test_suite *test = BOOST_TEST_SUITE("weighted_median test" ); |
65 | |
66 | test->add(BOOST_TEST_CASE(&test_stat)); |
67 | |
68 | return test; |
69 | } |
70 | |