guide_histogram_operators.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Copyright 2015-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_histogram_operators
  7. #include <boost/histogram.hpp>
  8. #include <cassert>
  9. #include <vector>
  10. int main() {
  11. using namespace boost::histogram;
  12. // make two histograms
  13. auto h1 = make_histogram(axis::regular<>(2, -1.0, 1.0));
  14. auto h2 = make_histogram(axis::regular<>(2, -1.0, 1.0));
  15. h1(-0.5); // counts are: 1 0
  16. h2(0.5); // counts are: 0 1
  17. // add them
  18. auto h3 = h1;
  19. h3 += h2; // counts are: 1 1
  20. // adding multiple histograms at once is likely to be optimized by the compiler so that
  21. // superfluous temporaries avoided, but no guarantees are given; use this equivalent
  22. // code when you want to make sure: h4 = h1; h4 += h2; h4 += h3;
  23. auto h4 = h1 + h2 + h3; // counts are: 2 2
  24. assert(h4.at(0) == 2 && h4.at(1) == 2);
  25. // multiply by number, h4 *= 2 also works
  26. auto h5 = h4 * 2; // counts are: 4 4
  27. // divide by number; s4 /= 4 also works
  28. auto h6 = h5 / 4; // counts are: 1 1
  29. assert(h6.at(0) == 1 && h6.at(1) == 1);
  30. assert(h6 != h5 && h5 == 4 * h6);
  31. // note the special effect of multiplication on weight_storage
  32. auto h = make_histogram_with(weight_storage(), axis::regular<>(2, -1.0, 1.0));
  33. h(-0.5);
  34. // counts are: 1 0
  35. assert(h.at(0).value() == 1 && h.at(1).value() == 0);
  36. auto h_sum = h + h;
  37. auto h_mul = 2 * h;
  38. // values are the same as expected...
  39. assert(h_sum.at(0).value() == h_mul.at(0).value());
  40. // ... but variances differ
  41. assert(h_sum.at(0).variance() == 2 && h_mul.at(0).variance() == 4);
  42. // equality operator checks variances, so histograms are not equal
  43. assert(h_sum != h_mul);
  44. }
  45. //]