NumCpp  2.8.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
41 {
42  namespace random
43  {
44  namespace detail
45  {
46  //============================================================================
47  // Method Description:
54  template<typename GeneratorType = std::mt19937>
55  bool bernoulli(GeneratorType& generator, double inP = 0.5)
56  {
57  if (inP < 0 || inP > 1)
58  {
59  THROW_INVALID_ARGUMENT_ERROR("input probability of success must be of the range [0, 1].");
60  }
61 
62  std::bernoulli_distribution dist(inP);
63  return dist(generator);
64  }
65 
66  //============================================================================
67  // Method Description:
76  template<typename GeneratorType = std::mt19937>
77  NdArray<bool> bernoulli(GeneratorType& generator, const Shape& inShape, double inP = 0.5)
78  {
79  if (inP < 0 || inP > 1)
80  {
81  THROW_INVALID_ARGUMENT_ERROR("input probability of success must be of the range [0, 1].");
82  }
83 
84  NdArray<bool> returnArray(inShape);
85 
86  std::bernoulli_distribution dist(inP);
87 
88  std::for_each(returnArray.begin(),
89  returnArray.end(),
90  [&generator, &dist](bool& value) -> void { value = dist(generator); });
91 
92  return returnArray;
93  }
94  } // namespace detail
95 
96  //============================================================================
97  // Method Description:
103  inline bool bernoulli(double inP = 0.5)
104  {
105  return detail::bernoulli(generator_, inP);
106  }
107 
108  //============================================================================
109  // Method Description:
117  inline NdArray<bool> bernoulli(const Shape& inShape, double inP = 0.5)
118  {
119  return detail::bernoulli(generator_, inShape, inP);
120  }
121  } // namespace random
122 } // namespace nc
#define THROW_INVALID_ARGUMENT_ERROR(msg)
Definition: Error.hpp:36
iterator end() noexcept
Definition: NdArrayCore.hpp:1479
iterator begin() noexcept
Definition: NdArrayCore.hpp:1171
A Shape Class for NdArrays.
Definition: Core/Shape.hpp:41
bool bernoulli(GeneratorType &generator, double inP=0.5)
Definition: Random/bernoulli.hpp:55
bool bernoulli(double inP=0.5)
Definition: Random/bernoulli.hpp:103
static std::mt19937_64 generator_
generator function
Definition: generator.hpp:37
void for_each(InputIt first, InputIt last, UnaryFunction f)
Definition: StlAlgorithms.hpp:227
Definition: Coordinate.hpp:45