NumCpp  2.12.1
A Templatized Header Only C++ Implementation of the Python NumPy Library
rand.hpp
Go to the documentation of this file.
1
29#pragma once
30
31#include <algorithm>
32#include <random>
33
35#include "NumCpp/Core/Shape.hpp"
36#include "NumCpp/NdArray.hpp"
38
39namespace nc::random
40{
41 namespace detail
42 {
43 //============================================================================
44 // Method Description:
53 template<typename dtype, typename GeneratorType = std::mt19937>
54 dtype rand(GeneratorType& generator)
55 {
57
58 std::uniform_real_distribution<dtype> dist(static_cast<dtype>(0.),
59 static_cast<dtype>(1.) - DtypeInfo<dtype>::epsilon());
60 return dist(generator);
61 }
62
63 //============================================================================
64 // Method Description:
75 template<typename dtype, typename GeneratorType = std::mt19937>
76 NdArray<dtype> rand(GeneratorType& generator, const Shape& inShape)
77 {
79
80 NdArray<dtype> returnArray(inShape);
81
82 std::uniform_real_distribution<dtype> dist(static_cast<dtype>(0.),
83 static_cast<dtype>(1.) - DtypeInfo<dtype>::epsilon());
84
85 std::for_each(returnArray.begin(),
86 returnArray.end(),
87 [&generator, &dist](dtype& value) -> void { value = dist(generator); });
88
89 return returnArray;
90 }
91 } // namespace detail
92
93 //============================================================================
94 // Method Description:
102 template<typename dtype>
103 dtype rand()
104 {
105 return detail::rand<dtype>(generator_);
106 }
107
108 //============================================================================
109 // Method Description:
119 template<typename dtype>
120 NdArray<dtype> rand(const Shape& inShape)
121 {
122 return detail::rand<dtype>(generator_, inShape);
123 }
124} // namespace nc::random
#define STATIC_ASSERT_FLOAT(dtype)
Definition: StaticAsserts.hpp:50
Holds info about the dtype.
Definition: DtypeInfo.hpp:41
Holds 1D and 2D arrays, the main work horse of the NumCpp library.
Definition: NdArrayCore.hpp:139
iterator end() noexcept
Definition: NdArrayCore.hpp:1623
iterator begin() noexcept
Definition: NdArrayCore.hpp:1315
A Shape Class for NdArrays.
Definition: Core/Shape.hpp:41
dtype rand(GeneratorType &generator)
Definition: rand.hpp:54
Definition: Random/bernoulli.hpp:41
dtype rand()
Definition: rand.hpp:103
static std::mt19937_64 generator_
generator function
Definition: generator.hpp:35
void for_each(InputIt first, InputIt last, UnaryFunction f)
Definition: StlAlgorithms.hpp:225