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