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/floating_point_comparison.hpp>
8 #include <boost/random.hpp>
9 #include <boost/accumulators/accumulators.hpp>
10 #include <boost/accumulators/statistics/stats.hpp>
11 #include <boost/accumulators/statistics/weighted_variance.hpp>
12
13 using namespace boost;
14 using namespace unit_test;
15 using namespace accumulators;
16
17 ///////////////////////////////////////////////////////////////////////////////
18 // test_stat
19 //
test_stat()20 void test_stat()
21 {
22 // lazy weighted_variance
23 accumulator_set<int, stats<tag::weighted_variance(lazy)>, int> acc1;
24
25 acc1(1, weight = 2); // 2
26 acc1(2, weight = 3); // 6
27 acc1(3, weight = 1); // 3
28 acc1(4, weight = 4); // 16
29 acc1(5, weight = 1); // 5
30
31 // weighted_mean = (2+6+3+16+5) / (2+3+1+4+1) = 32 / 11 = 2.9090909090909090909090909090909
32
33 BOOST_CHECK_EQUAL(5u, count(acc1));
34 BOOST_CHECK_CLOSE(2.9090909, weighted_mean(acc1), 1e-5);
35 BOOST_CHECK_CLOSE(10.1818182, accumulators::weighted_moment<2>(acc1), 1e-5);
36 BOOST_CHECK_CLOSE(1.7190083, weighted_variance(acc1), 1e-5);
37
38 accumulator_set<int, stats<tag::weighted_variance>, int> acc2;
39
40 acc2(1, weight = 2);
41 acc2(2, weight = 3);
42 acc2(3, weight = 1);
43 acc2(4, weight = 4);
44 acc2(5, weight = 1);
45
46 BOOST_CHECK_EQUAL(5u, count(acc2));
47 BOOST_CHECK_CLOSE(2.9090909, weighted_mean(acc2), 1e-5);
48 BOOST_CHECK_CLOSE(1.7190083, weighted_variance(acc2), 1e-5);
49
50 // check lazy and immediate variance with random numbers
51
52 // two random number generators
53 boost::lagged_fibonacci607 rng;
54 boost::normal_distribution<> mean_sigma(0,1);
55 boost::variate_generator<boost::lagged_fibonacci607&, boost::normal_distribution<> > normal(rng, mean_sigma);
56
57 accumulator_set<double, stats<tag::weighted_variance(lazy)>, double > acc_lazy;
58 accumulator_set<double, stats<tag::weighted_variance>, double > acc_immediate;
59
60 for (std::size_t i=0; i<10000; ++i)
61 {
62 double value = normal();
63 acc_lazy(value, weight = rng());
64 acc_immediate(value, weight = rng());
65 }
66
67 BOOST_CHECK_CLOSE(1., weighted_variance(acc_lazy), 5.);
68 BOOST_CHECK_CLOSE(1., weighted_variance(acc_immediate), 5.);
69 }
70
71 ///////////////////////////////////////////////////////////////////////////////
72 // init_unit_test_suite
73 //
init_unit_test_suite(int argc,char * argv[])74 test_suite* init_unit_test_suite( int argc, char* argv[] )
75 {
76 test_suite *test = BOOST_TEST_SUITE("weighted_variance test");
77
78 test->add(BOOST_TEST_CASE(&test_stat));
79
80 return test;
81 }
82