NumCpp  2.11.0
A Templatized Header Only C++ Implementation of the Python NumPy Library
Random/bernoulli.hpp
Go to the documentation of this file.
1 #pragma once
29 
30 #include <algorithm>
31 #include <random>
32 #include <string>
33 
36 #include "NumCpp/Core/Shape.hpp"
37 #include "NumCpp/NdArray.hpp"
39 
40 namespace nc::random
41 {
42  namespace detail
43  {
44  //============================================================================
45  // Method Description:
52  template<typename GeneratorType = std::mt19937>
53  bool bernoulli(GeneratorType& generator, double inP = 0.5)
54  {
55  if (inP < 0 || inP > 1)
56  {
57  THROW_INVALID_ARGUMENT_ERROR("input probability of success must be of the range [0, 1].");
58  }
59 
60  std::bernoulli_distribution dist(inP);
61  return dist(generator);
62  }
63 
64  //============================================================================
65  // Method Description:
74  template<typename GeneratorType = std::mt19937>
75  NdArray<bool> bernoulli(GeneratorType& generator, const Shape& inShape, double inP = 0.5)
76  {
77  if (inP < 0 || inP > 1)
78  {
79  THROW_INVALID_ARGUMENT_ERROR("input probability of success must be of the range [0, 1].");
80  }
81 
82  NdArray<bool> returnArray(inShape);
83 
84  std::bernoulli_distribution dist(inP);
85 
86  std::for_each(returnArray.begin(),
87  returnArray.end(),
88  [&generator, &dist](bool& value) -> void { value = dist(generator); });
89 
90  return returnArray;
91  }
92  } // namespace detail
93 
94  //============================================================================
95  // Method Description:
101  inline bool bernoulli(double inP = 0.5)
102  {
103  return detail::bernoulli(generator_, inP);
104  }
105 
106  //============================================================================
107  // Method Description:
115  inline NdArray<bool> bernoulli(const Shape& inShape, double inP = 0.5)
116  {
117  return detail::bernoulli(generator_, inShape, inP);
118  }
119 } // namespace nc::random
#define THROW_INVALID_ARGUMENT_ERROR(msg)
Definition: Error.hpp:37
iterator end() noexcept
Definition: NdArrayCore.hpp:1576
iterator begin() noexcept
Definition: NdArrayCore.hpp:1268
A Shape Class for NdArrays.
Definition: Core/Shape.hpp:41
bool bernoulli(GeneratorType &generator, double inP=0.5)
Definition: Random/bernoulli.hpp:53
Definition: Random/bernoulli.hpp:41
bool bernoulli(double inP=0.5)
Definition: Random/bernoulli.hpp:101
static std::mt19937_64 generator_
generator function
Definition: generator.hpp:35
void for_each(InputIt first, InputIt last, UnaryFunction f)
Definition: StlAlgorithms.hpp:225