NumCpp  2.3.0
A Templatized Header Only C++ Implementation of the Python NumPy Library
histogram.hpp
Go to the documentation of this file.
1 #pragma once
29 
32 #include "NumCpp/Core/Types.hpp"
35 #include "NumCpp/NdArray.hpp"
36 
37 #include <string>
38 #include <utility>
39 
40 namespace nc
41 {
42  //============================================================================
43  // Method Description:
55  template<typename dtype>
56  std::pair<NdArray<uint32>, NdArray<double> > histogram(const NdArray<dtype>& inArray, uint32 inNumBins = 10)
57  {
59 
60  if (inNumBins == 0)
61  {
62  THROW_INVALID_ARGUMENT_ERROR("number of bins must be positive.");
63  }
64 
65  NdArray<uint32> histo = zeros<uint32>(1, inNumBins);
66 
67  constexpr bool useEndPoint = true;
68  NdArray<double> binEdges = linspace(static_cast<double>(inArray.min().item()),
69  static_cast<double>(inArray.max().item()), inNumBins + 1, useEndPoint);
70 
71  for (uint32 i = 0; i < inArray.size(); ++i)
72  {
73  // binary search to find the bin idx
74  constexpr bool keepSearching = true;
75  uint32 lowIdx = 0;
76  uint32 highIdx = binEdges.size() - 1;
77  while (keepSearching)
78  {
79  const uint32 idx = (lowIdx + highIdx) / 2; // integer division
80  if (lowIdx == highIdx || lowIdx == highIdx - 1)
81  {
82  // we found the bin
83  ++histo[lowIdx];
84  break;
85  }
86 
87  if (inArray[i] > binEdges[idx])
88  {
89  lowIdx = idx;
90  }
91  else if (inArray[i] < binEdges[idx])
92  {
93  highIdx = idx;
94  }
95  else
96  {
97  // we found the bin
98  ++histo[idx];
99  break;
100  }
101  }
102  }
103 
104  return std::make_pair(histo, binEdges);
105  }
106 } // namespace nc
StaticAsserts.hpp
nc::NdArray::item
value_type item() const
Definition: NdArrayCore.hpp:2957
zeros.hpp
Error.hpp
STATIC_ASSERT_ARITHMETIC
#define STATIC_ASSERT_ARITHMETIC(dtype)
Definition: StaticAsserts.hpp:37
nc::NdArray::max
NdArray< dtype > max(Axis inAxis=Axis::NONE) const
Definition: NdArrayCore.hpp:2978
nc::NdArray< double >
nc::uint32
std::uint32_t uint32
Definition: Types.hpp:40
linspace.hpp
NdArray.hpp
nc::NdArray::size
size_type size() const noexcept
Definition: NdArrayCore.hpp:4325
nc::linspace
NdArray< dtype > linspace(dtype inStart, dtype inStop, uint32 inNum=50, bool endPoint=true)
Definition: linspace.hpp:62
nc
Definition: Coordinate.hpp:44
THROW_INVALID_ARGUMENT_ERROR
#define THROW_INVALID_ARGUMENT_ERROR(msg)
Definition: Error.hpp:36
Types.hpp
nc::histogram
std::pair< NdArray< uint32 >, NdArray< double > > histogram(const NdArray< dtype > &inArray, uint32 inNumBins=10)
Definition: histogram.hpp:56
nc::NdArray::min
NdArray< dtype > min(Axis inAxis=Axis::NONE) const
Definition: NdArrayCore.hpp:3035