NumCpp  2.7.0
A Templatized Header Only C++ Implementation of the Python NumPy Library
binomial.hpp
Go to the documentation of this file.
1 #pragma once
29 
32 #include "NumCpp/Core/Shape.hpp"
33 #include "NumCpp/NdArray.hpp"
35 
36 #include <algorithm>
37 #include <random>
38 #include <string>
39 
40 namespace nc
41 {
42  namespace random
43  {
44  //============================================================================
45  // Method Description:
54  template<typename dtype>
55  dtype binomial(dtype inN, double inP = 0.5)
56  {
57  STATIC_ASSERT_INTEGER(dtype);
58 
59  if (inN < 0)
60  {
61  THROW_INVALID_ARGUMENT_ERROR("input number of trials must be greater than or equal to zero.");
62  }
63 
64  if (inP < 0 || inP > 1)
65  {
66  THROW_INVALID_ARGUMENT_ERROR("input probability of sucess must be of the range [0, 1].");
67  }
68 
69  std::binomial_distribution<dtype> dist(inN, inP);
70  return dist(generator_);
71  }
72 
73  //============================================================================
74  // Method Description:
85  template<typename dtype>
86  NdArray<dtype> binomial(const Shape& inShape, dtype inN, double inP = 0.5)
87  {
88  STATIC_ASSERT_INTEGER(dtype);
89 
90  if (inN < 0)
91  {
92  THROW_INVALID_ARGUMENT_ERROR("input number of trials must be greater than or equal to zero.");
93  }
94 
95  if (inP < 0 || inP > 1)
96  {
97  THROW_INVALID_ARGUMENT_ERROR("input probability of sucess must be of the range [0, 1].");
98  }
99 
100  NdArray<dtype> returnArray(inShape);
101 
102  std::binomial_distribution<dtype> dist(inN, inP);
103 
104  std::for_each(returnArray.begin(), returnArray.end(),
105  [&dist](dtype& value) -> void
106  {
107  value = dist(generator_);
108  });
109 
110  return returnArray;
111  }
112  } // namespace random
113 } // namespace nc
#define THROW_INVALID_ARGUMENT_ERROR(msg)
Definition: Error.hpp:36
#define STATIC_ASSERT_INTEGER(dtype)
Definition: StaticAsserts.hpp:40
Holds 1D and 2D arrays, the main work horse of the NumCpp library.
Definition: NdArrayCore.hpp:72
iterator end() noexcept
Definition: NdArrayCore.hpp:1474
iterator begin() noexcept
Definition: NdArrayCore.hpp:1166
A Shape Class for NdArrays.
Definition: Core/Shape.hpp:41
dtype binomial(dtype inN, double inP=0.5)
Definition: binomial.hpp:55
static std::mt19937_64 generator_
generator function
Definition: generator.hpp:39
void for_each(InputIt first, InputIt last, UnaryFunction f)
Definition: StlAlgorithms.hpp:213
Definition: Coordinate.hpp:45