]>
Commit | Line | Data |
---|---|---|
92f5a8d4 TL |
1 | // Copyright 2018 Hans Dembinski |
2 | // | |
3 | // Distributed under the Boost Software License, Version 1.0. | |
4 | // (See accompanying file LICENSE_1_0.txt | |
5 | // or copy at http://www.boost.org/LICENSE_1_0.txt) | |
6 | ||
7 | //[ guide_stdlib_algorithms | |
8 | ||
9 | #include <boost/histogram.hpp> | |
10 | #include <cassert> | |
11 | ||
12 | #include <algorithm> // fill, any_of, min_element, max_element | |
13 | #include <cmath> // sqrt | |
14 | #include <numeric> // partial_sum, inner_product | |
15 | ||
16 | int main() { | |
17 | using namespace boost::histogram; | |
18 | ||
19 | // make histogram that represents a probability density function (PDF) | |
20 | auto h1 = make_histogram(axis::regular<>(4, 1.0, 3.0)); | |
21 | ||
22 | // make indexed range to skip underflow and overflow cells | |
23 | auto ind = indexed(h1); | |
24 | ||
25 | // use std::fill to set all counters to 0.25 (except under- and overflow counters) | |
26 | std::fill(ind.begin(), ind.end(), 0.25); | |
27 | ||
28 | // compute the cumulative density function (CDF), overriding cell values | |
29 | std::partial_sum(ind.begin(), ind.end(), ind.begin()); | |
30 | ||
31 | assert(h1.at(-1) == 0.00); | |
32 | assert(h1.at(0) == 0.25); | |
33 | assert(h1.at(1) == 0.50); | |
34 | assert(h1.at(2) == 0.75); | |
35 | assert(h1.at(3) == 1.00); | |
36 | assert(h1.at(4) == 0.00); | |
37 | ||
38 | // use any_of to check if any cell values are smaller than 0.1, | |
39 | auto b = std::any_of(ind.begin(), ind.end(), [](const auto& x) { return x < 0.1; }); | |
40 | assert(b == false); // under- and overflow cells are zero, but skipped | |
41 | ||
42 | // find minimum element | |
43 | auto min_it = std::min_element(ind.begin(), ind.end()); | |
44 | assert(*min_it == 0.25); // under- and overflow cells are skipped | |
45 | ||
46 | // find maximum element | |
47 | auto max_it = std::max_element(ind.begin(), ind.end()); | |
48 | assert(*max_it == 1.0); | |
49 | ||
50 | // make second PDF | |
51 | auto h2 = make_histogram(axis::regular<>(4, 1.0, 4.0)); | |
52 | h2.at(0) = 0.1; | |
53 | h2.at(1) = 0.3; | |
54 | h2.at(2) = 0.2; | |
55 | h2.at(3) = 0.4; | |
56 | ||
57 | // computing cosine similiarity: cos(theta) = A dot B / sqrt((A dot A) * (B dot B)) | |
58 | auto ind2 = indexed(h2); | |
59 | const auto aa = std::inner_product(ind.begin(), ind.end(), ind.begin(), 0.0); | |
60 | const auto bb = std::inner_product(ind2.begin(), ind2.end(), ind2.begin(), 0.0); | |
61 | const auto ab = std::inner_product(ind.begin(), ind.end(), ind2.begin(), 0.0); | |
62 | const auto cos_sim = ab / std::sqrt(aa * bb); | |
63 | ||
64 | assert(std::abs(cos_sim - 0.967) < 1e-2); | |
65 | } | |
66 | ||
67 | //] |