guide_stdlib_algorithms.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. //[ guide_stdlib_algorithms
  7. #include <boost/histogram.hpp>
  8. #include <cassert>
  9. #include <algorithm> // fill, any_of, min_element, max_element
  10. #include <cmath> // sqrt
  11. #include <numeric> // partial_sum, inner_product
  12. int main() {
  13. using namespace boost::histogram;
  14. // make histogram that represents a probability density function (PDF)
  15. auto h1 = make_histogram(axis::regular<>(4, 1.0, 3.0));
  16. // make indexed range to skip underflow and overflow cells
  17. auto ind = indexed(h1);
  18. // use std::fill to set all counters to 0.25 (except under- and overflow counters)
  19. std::fill(ind.begin(), ind.end(), 0.25);
  20. // compute the cumulative density function (CDF), overriding cell values
  21. std::partial_sum(ind.begin(), ind.end(), ind.begin());
  22. assert(h1.at(-1) == 0.00);
  23. assert(h1.at(0) == 0.25);
  24. assert(h1.at(1) == 0.50);
  25. assert(h1.at(2) == 0.75);
  26. assert(h1.at(3) == 1.00);
  27. assert(h1.at(4) == 0.00);
  28. // use any_of to check if any cell values are smaller than 0.1,
  29. auto b = std::any_of(ind.begin(), ind.end(), [](const auto& x) { return x < 0.1; });
  30. assert(b == false); // under- and overflow cells are zero, but skipped
  31. // find minimum element
  32. auto min_it = std::min_element(ind.begin(), ind.end());
  33. assert(*min_it == 0.25); // under- and overflow cells are skipped
  34. // find maximum element
  35. auto max_it = std::max_element(ind.begin(), ind.end());
  36. assert(*max_it == 1.0);
  37. // make second PDF
  38. auto h2 = make_histogram(axis::regular<>(4, 1.0, 4.0));
  39. h2.at(0) = 0.1;
  40. h2.at(1) = 0.3;
  41. h2.at(2) = 0.2;
  42. h2.at(3) = 0.4;
  43. // computing cosine similiarity: cos(theta) = A dot B / sqrt((A dot A) * (B dot B))
  44. auto ind2 = indexed(h2);
  45. const auto aa = std::inner_product(ind.begin(), ind.end(), ind.begin(), 0.0);
  46. const auto bb = std::inner_product(ind2.begin(), ind2.end(), ind2.begin(), 0.0);
  47. const auto ab = std::inner_product(ind.begin(), ind.end(), ind2.begin(), 0.0);
  48. const auto cos_sim = ab / std::sqrt(aa * bb);
  49. assert(std::abs(cos_sim - 0.967) < 1e-2);
  50. }
  51. //]