gpt4 book ai didi

c++ - 在 .h 文件中声明正态分布生成器

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:42:32 25 4
gpt4 key购买 nike

我有一个成员函数,我想生成大量高斯分布的随机数,但我不想在每次调用该函数时都初始化随机数生成器,认为这样会更慢。我想我可以在 .h 文件中声明随机数生成器并在构造函数中对其进行初始化,但我不确定执行此操作的语法,甚至不确定它是否有效。另外,我不确定这是否确实有必要节省计算时间。

换句话说,我想在 .h 文件中创建一个 std::normal_distribution 生成器,而不指定参数。声明它的标准方法是

std::default_random_engine generator;

std::normal_distribution<double> distribution1(mu, sigma);

但是,我不确定这是否适用于 .h 文件,因为这实际上实例化了类。我在想也许我应该声明一个指向正态分布对象的指针,或者类似的东西,但我不确定这个的正确语法。我想要某种形式的东西

class my_rand{
my_rand(double, double);
std::default_random_engine generator;
std::normal_distribution<double> distribution;
double return_rand();
}

my_rand::my_rand(double mu, double sigma){
distribution.param(mu,sigma);
}

double my_rand::return_rand(){
return distribution(generator);
}

最佳答案

几年前,我编写了几个类来封装标准的随机生成器和分布类。这是我的类(class)的样子:有几种方法可以为生成器和不同的生成器提供种子;类 RandomEngineRandomDistribution 无缝地一起工作,因为它们只是包装类中的静态方法。在类之后还有 typedefs 以减少输入量:分别是 RERD

随机生成器.h

#ifndef RANDOM_GENERATOR_H
#define RANDOM_GENERATOR_H

#include <limits>
#include <chrono>
#include <random>

class RandomEngine {
public:
using Clock = std::conditional_t<std::chrono::high_resolution_clock::is_steady,
std::chrono::high_resolution_clock,
std::chrono::steady_clock>;

// Used To Determine Which Seeding Process To Use
enum SeedType {
USE_CHRONO_CLOCK,
USE_RANDOM_DEVICE,
USE_SEED_VALUE,
USE_SEED_SEQ,
}; // SeedType

// This Enum Is Not In Use - It Is A Visual Reference Only; But If User Wants To
// Use It For Their Own Pupose They Are Free To Do So.
enum EngineType {
// Default Random Engine
DEFAULT_RANDOM_ENGINE,

// Linear Congruential Engines
MINSTD_RAND0,
MINSTD_RAND,

// Mersenne Twister Engines
MT19937,
MT19937_64,

// Subtract With Carry Engines
RANLUX24_BASE,
RANLUX48_BASE,

// Discard Block Engines
RANLUX24,
RANLUX48,

// Shuffle Order Engines
KNUTH_B,

}; // EngineType

protected:
RandomEngine(){}

// Internal Helper Function
// ---------------------------------------------------------------------------
// getRandomDevice()
static std::random_device& getRandomDevice() {
static std::random_device device{};
return device;
} // getRandomDevice

public:
// ---------------------------------------------------------------------------
// getTimeNow()
static unsigned int getTimeNow() {
unsigned int now = static_cast<unsigned int>(Clock::now().time_since_epoch().count());
return now;
} // getTimeNow

// ---------------------------------------------------------------------------
// getDefaultRandomEngine()
static std::default_random_engine& getDefaultRandomEngine( SeedType type, unsigned seedValue = 0, std::seed_seq& seq = std::seed_seq{} ) {
static std::default_random_engine engine{};

switch ( type ) {
case USE_CHRONO_CLOCK: {
engine.seed( getTimeNow() );
break;
}
case USE_SEED_VALUE: {
engine.seed( seedValue );
break;
}
case USE_SEED_SEQ: {
engine.seed( seq );
break;
}
default: {
engine.seed( getRandomDevice()() );
break;
}
}

return engine;
} // getDefaultRandomEngine

// ---------------------------------------------------------------------------
// getMinStd_Rand0()
static std::minstd_rand0& getMinStd_Rand0( SeedType type, unsigned seedValue = 0, std::seed_seq& seq = std::seed_seq{} ) {
static std::minstd_rand0 engine{};

switch ( type ) {
case USE_CHRONO_CLOCK: {
engine.seed( getTimeNow() );
break;
}
case USE_SEED_VALUE: {
engine.seed( seedValue );
break;
}
case USE_SEED_SEQ: {
engine.seed( seq );
break;
}
default: {
engine.seed( getRandomDevice()() );
break;
}
}

return engine;
} // getMinStd_Rand0

// ---------------------------------------------------------------------------
// getMinStd_Rand()
static std::minstd_rand& getMinStd_Rand( SeedType type, unsigned seedValue = 0, std::seed_seq& seq = std::seed_seq{} ) {
static std::minstd_rand engine{};

switch( type ) {
case USE_CHRONO_CLOCK: {
engine.seed( getTimeNow() );
break;
}
case USE_SEED_VALUE: {
engine.seed( seedValue );
break;
}
case USE_SEED_SEQ: {
engine.seed(seq);
break;
}
default: {
engine.seed( getRandomDevice()() );
break;
}
}

return engine;
} // getMinStd_Rand

// ---------------------------------------------------------------------------
// getMt19937()
static std::mt19937& getMt19937( SeedType type, unsigned seedValue = 0, std::seed_seq& seq = std::seed_seq{} ) {
static std::mt19937 engine{};

switch ( type ) {
case USE_CHRONO_CLOCK: {
engine.seed( getTimeNow() );
break;
}
case USE_SEED_VALUE: {
engine.seed( seedValue );
break;
}
case USE_SEED_SEQ: {
engine.seed( seq );
break;
}
default: {
engine.seed( getRandomDevice()() );
break;
}
}

return engine;
} //getMt19937

// ---------------------------------------------------------------------------
// getMt19937_64()
static std::mt19937_64& getMt19937_64( SeedType type, unsigned seedValue = 0, std::seed_seq& seq = std::seed_seq{} ) {
static std::mt19937_64 engine{};

switch ( type ) {
case USE_CHRONO_CLOCK: {
engine.seed( getTimeNow() );
break;
}
case USE_SEED_VALUE: {
engine.seed( seedValue );
break;
}
case USE_SEED_SEQ: {
engine.seed( seq );
break;
}
default: {
engine.seed( getRandomDevice()() );
break;
}
}

return engine;
} // getMt19937_64

// ---------------------------------------------------------------------------
// getRanLux24_base()
static std::ranlux24_base& getRanLux24_base( SeedType type, unsigned seedValue = 0, std::seed_seq& seq = std::seed_seq{} ) {
static std::ranlux24_base engine{};

switch ( type ) {
case USE_CHRONO_CLOCK: {
engine.seed( getTimeNow() );
break;
}
case USE_SEED_VALUE: {
engine.seed( seedValue );
break;
}
case USE_SEED_SEQ: {
engine.seed( seq );
break;
}
default: {
engine.seed( getRandomDevice()() );
break;
}
}

return engine;
} // getRanLux24_base

// ---------------------------------------------------------------------------
// getRanLux48_base()
static std::ranlux48_base& getRanLux48_base( SeedType type, unsigned seedValue = 0, std::seed_seq& seq = std::seed_seq{} ) {
static std::ranlux48_base engine{};

switch ( type ) {
case USE_CHRONO_CLOCK: {
engine.seed( getTimeNow() );
break;
}
case USE_SEED_VALUE: {
engine.seed( seedValue );
break;
}
case USE_SEED_SEQ: {
engine.seed( seq );
break;
}
default: {
engine.seed( getRandomDevice()() );
break;
}
}

return engine;
} // getRanLux48_base

// ---------------------------------------------------------------------------
// getRanLux24()
static std::ranlux24& getRanLux24( SeedType type, unsigned seedValue = 0, std::seed_seq& seq = std::seed_seq{} ) {
static std::ranlux24 engine{};

switch ( type ) {
case USE_CHRONO_CLOCK: {
engine.seed( getTimeNow() );
break;
}
case USE_SEED_VALUE: {
engine.seed( seedValue );
break;
}
case USE_SEED_SEQ: {
engine.seed( seq );
break;
}
default: {
engine.seed( getRandomDevice()() );
break;
}
}

return engine;
} // getRanLux24

// ---------------------------------------------------------------------------
// getRanLux48()
static std::ranlux48& getRanLux48( SeedType type, unsigned seedValue = 0, std::seed_seq& seq = std::seed_seq{} ) {
static std::ranlux48 engine{};

switch ( type ) {
case USE_CHRONO_CLOCK: {
engine.seed( getTimeNow() );
break;
}
case USE_SEED_VALUE: {
engine.seed( seedValue );
break;
}
case USE_SEED_SEQ: {
engine.seed( seq );
break;
}
default: {
engine.seed( getRandomDevice()() );
break;
}
}

return engine;
} //getRanLux48

}; // RandomEngine

class RandomDistribution {
public:
// This Enum Is Not In Use - It Is A Visual Reference Only; But If User Wants To
// Use It For Their Own Pupose They Are Free To Do So.
enum DistributionType {
// Uniform Distributions
UNIFORM_INT,
UNIFORM_INT_DISTRIBUTION,
UNIFORM_REAL,
UNIFORM_REAL_DISTRIBUTION,
// GENERATE_CANONICAL, - This is a function template and not a class template use it directly form std:: <random> c++11

// Bernoulli Distributions
BERNOULLI_DISTRIBUTION,
BINOMAIL_DISTRIBUTION,
NEGATIVE_BINOMIAL_DISTRIBUTION,
GEOMETRIC_DISTRIBUTION,

// Poisson Distributions
POISSON_DISTRIBUTION,
EXPONENTIAL_DISTRIBUTION,
GAMMA_DISTRIBUTION,
WEIBULL_DISTRIBUTION,
EXTREME_VALUE_DISTRIBUTION,

// Normal Distributions
NORMAL_DISTRIBUTION,
LOGNORMAL_DISTRIBUTION,
CHI_SQUARED_DISTRIBUTION,
CAUCHY_DISTRIBUTION,
FISHER_F_DISTRIBUTION,
STUDENT_T_DISTRIBUTION,

// Sampling Distributions
DISCRETE_DISTRIBUTION,
PIECEWISE_CONSTANT_DISTRIBUTION,
PIECEWISE_LINEAR_DISTRIBUTION
}; // DistributionType

protected:
RandomDistribution(){}

public:

// UNIFORM DISTRIBUTIONS

// ---------------------------------------------------------------------------
// getUniformIntDistribution()
template<class IntType = int>
static std::uniform_int_distribution<IntType>& getUniformIntDistribution( IntType lowerBound = 0, IntType upperBound = (std::numeric_limits<IntType>::max)() ) {
static std::uniform_int_distribution<IntType> dist( lowerBound, upperBound );
return dist;
} // getUniformIntDistribution

// ---------------------------------------------------------------------------
// getUniformRealDistribution()
template<class RealType = double>
static std::uniform_real_distribution<RealType>& getUniformRealDistribution( RealType lowerBound = 0.0, RealType upperBound = 1.0 ) {
static std::uniform_real_distribution<RealType> dist( lowerBound, upperBound );
return dist;
} // getUniformRealDistribution



// BERNOULLI DISTRIBUTIONS

// ---------------------------------------------------------------------------
// getBernoulliDistribution()
static std::bernoulli_distribution& getBernoulliDistribution( double probability = 0.5 ) {
static std::bernoulli_distribution dist( probability );
return dist;
} // getBernoulliDistribution

// ---------------------------------------------------------------------------
// getBinomialDistribution()
template<class IntType = int>
static std::binomial_distribution<IntType>& getBinomialDistribution( IntType numTrials = 1, double probability = 0.5 ) {
static std::binomial_distribution<IntType> dist( numTrials, probability );
return dist;
} // getBinomialDistribution

// ---------------------------------------------------------------------------
// getNegativeBinomialDistribution()
template<class IntType = int>
static std::negative_binomial_distribution<IntType>& getNegativeBinomialDistribution( IntType numTrialFailures = 1, double probability = 0.5 ) {
static std::negative_binomial_distribution<IntType> dist( numTrialFailures, probability );
return dist;
} // getNegativeBinomialDistribution

// ---------------------------------------------------------------------------
// getGeometricDistribution()
template<class IntType = int>
static std::geometric_distribution<IntType>& getGeometricDistribution( double probability = 0.5 ) {
static std::geometric_distribution<IntType> dist( probability );
return dist;
} // getGeometricDistribution



// POISSON DISTRIBUTIONS

// ---------------------------------------------------------------------------
// getPoissonDistribution()
template<class IntType = int>
static std::poisson_distribution<IntType>& getPoissonDistribution( double mean = 1.0 ) {
static std::poisson_distribution<IntType> dist( mean );
return dist;
} // getPoissonDistribution

// ---------------------------------------------------------------------------
// getExponentialDistribution()
template<class RealType = double>
static std::exponential_distribution<RealType>& getExponentialDistribution( RealType rate = 1.0 ) {
static std::exponential_distribution<RealType> dist( rate );
return dist;
} // getExponentialDistribution

// ---------------------------------------------------------------------------
// getGammDistribution()
template<class RealType = double>
static std::gamma_distribution<RealType>& getGammaDistribution( RealType alpha_shape = 1.0, RealType beta_scale = 1.0 ) {
static std::gamma_distribution<RealType> dist( alpha_shape, beta_scale );
return dist;
} // getGammaDistribution

// ---------------------------------------------------------------------------
// getWeibullDistribution()
template<class RealType = double>
static std::weibull_distribution<RealType>& getWeibullDistribution( RealType alpha_shape = 1.0, RealType beta_scale = 1.0 ) {
static std::weibull_distribution<RealType> dist( alpha_shape, beta_scale );
return dist;
} // getWeibullDistribution

// ---------------------------------------------------------------------------
// getExtremeValueDistribution()
template<class RealType = double>
static std::extreme_value_distribution<RealType>& getExtremeValueDistribution( RealType location = 0.0, RealType scale = 1.0 ) {
static std::extreme_value_distribution<RealType> dist( location, scale );
return dist;
} // getExtremeValueDistribution


// NORMAL DISTRIBUTIONS

// ---------------------------------------------------------------------------
// getNormalDistribution()
template<class RealType = double>
static std::normal_distribution<RealType>& getNormalDistribution( RealType mean = 0.0, RealType stddev = 1.0 ) {
static std::normal_distribution<RealType> dist( mean, stddev );
return dist;
} // getNormaDistribution

// ---------------------------------------------------------------------------
// getLogNormalDistribution()
template<class RealType = double>
static std::lognormal_distribution<RealType>& getLogNormalDistribution( RealType logScale = 0.0, RealType shape = 1.0 ) {
static std::lognormal_distribution<RealType> dist( logScale, shape );
return dist;
} // getLogNormalDistribution

// ---------------------------------------------------------------------------
// getChiSquaredDistribution()
template<class RealType = double>
static std::chi_squared_distribution<RealType>& getChiSquaredDistribution( RealType degreesOfFreedom = 1.0 ) {
static std::chi_squared_distribution<RealType> dist( degreesOfFreedom );
return dist;
} // getChiSquaredDistribution

// ---------------------------------------------------------------------------
// getCauchyDistribution()
template<class RealType = double>
static std::cauchy_distribution<RealType>& getCauchyDistribution( RealType location = 0.0, RealType scale = 1.0 ) {
static std::cauchy_distribution<RealType> dist( location, scale );
return dist;
} // getCauchyDistribution

// ---------------------------------------------------------------------------
// getFisherFDistribution() Both m,n are degress of freedom
template<class RealType = double>
static std::fisher_f_distribution<RealType>& getFisherFDistribution( RealType m = 1.0, RealType n = 1.0 ) {
static std::fisher_f_distribution<RealType> dist( m, n );
return dist;
} // getFisherFDistribution

// ---------------------------------------------------------------------------
// getStudentTDistribution()
template<class RealType = double>
static std::student_t_distribution<RealType>& getStudentTDistribution( RealType degreesOfFreedom = 1.0 ) {
static std::student_t_distribution<RealType> dist( degreesOfFreedom );
return dist;
} // getStudentTDistribution


// SAMPLING DISTRIBUTIONS

// ---------------------------------------------------------------------------
// getDiscreteDistribution()
template<class IntType = int>
static std::discrete_distribution<IntType>& getDiscreteDistribution() {
static std::discrete_distribution<IntType> dist;
return dist;
} // getDiscreteDistribution

// ---------------------------------------------------------------------------
// getDiscreteDistribution()
template<class IntType = int, class InputIt>
static std::discrete_distribution<IntType>& getDiscreteDistribution( InputIt first, InputIt last ) {
static std::discrete_distribution<IntType> dist( first, last );
return dist;
} // getDiscreteDistribution

// ---------------------------------------------------------------------------
// getDiscreteDistribution()
template<class IntType = int>
static std::discrete_distribution<IntType>& getDiscreteDistribution( std::initializer_list<double> weights ) {
static std::discrete_distribution<IntType> dist( weights );
return dist;
} // getDiscreteDistribution

// ---------------------------------------------------------------------------
// getDiscreteDistribution()
template<class IntType = int, class UnaryOperation>
static std::discrete_distribution<IntType>& getDiscreteDistribution( std::size_t count, double xmin, double xmax, UnaryOperation unary_op ) {
static std::discrete_distribution<IntType> dist( count, xmin, xmax, unary_op );
return dist;
} // getDiscreteDistribution

// ---------------------------------------------------------------------------
// getPiecewiseConstantDistribution()
template<class RealType = double>
static std::piecewise_constant_distribution<RealType>& getPiecewiseConstantDistribution() {
static std::piecewise_constant_distribution<RealType> dist;
return dist;
} // getPiecewiseConstantDistribution

// ---------------------------------------------------------------------------
// getPiecewiseConstantDistribution()
template<class RealType = double, class InputIt1, class InputIt2>
static std::piecewise_constant_distribution<RealType>& getPiecewiseConstantDistribution( InputIt1 first_i, InputIt1 last_i, InputIt2 first_w ) {
static std::piecewise_constant_distribution<RealType> dist( first_i, last_i, first_w );
return dist;
} // getPiecewiseConstantDistribution

// ---------------------------------------------------------------------------
// getPiecewiseConstantDistribution()
template<class RealType = double, class UnaryOperation>
static std::piecewise_constant_distribution<RealType>& getPiecewiseConstantDistribution( std::initializer_list<RealType> bl, UnaryOperation fw ) {
static std::piecewise_constant_distribution<RealType> dist( bl, fw );
return dist;
} // getPiecewiseConstantDistribution

// ---------------------------------------------------------------------------
// getPiecewiseConstantDistribution()
template<class RealType = double, class UnaryOperation>
static std::piecewise_constant_distribution<RealType>& getPiecewiseConstantDistribution( std::size_t nw, RealType xmin, RealType xmax, UnaryOperation fw ) {
static std::piecewise_constant_distribution<RealType> dist( nw, xmin, xmax, fw );
return dist;
} // getPiecewiseConstantDistribution

// ---------------------------------------------------------------------------
// getPiecewiseLinearDistribution()
template<class RealType = double>
static std::piecewise_linear_distribution<RealType>& getPiecewiseLinearDistribution() {
static std::piecewise_linear_distribution<RealType> dist;
return dist;
} // getPiecewiseLinearDistribution

// ---------------------------------------------------------------------------
// getPiecewiseLinearDistribution()
template<class RealType = double, class InputIt1, class InputIt2>
static std::piecewise_linear_distribution<RealType>& getPiecewiseLinearDistribution( InputIt1 first_i, InputIt1 last_i, InputIt2 first_w ) {
static std::piecewise_linear_distribution<RealType> dist( first_i, last_i, first_w );
return dist;
} // getPiecewiseLinearDistribution

// ---------------------------------------------------------------------------
// getPiecewiseLinearDistribution()
template<class RealType = double, class UnaryOperation>
static std::piecewise_linear_distribution<RealType>& getPiecewiseLinearDistribution( std::initializer_list<RealType> bl, UnaryOperation fw ) {
static std::piecewise_linear_distribution<RealType> dist( bl, fw );
return dist;
} // getPiecewiseLinearDistribution

// ---------------------------------------------------------------------------
// getPiecewiseLinearDistribution()
template<class RealType = double, class UnaryOperation>
static std::piecewise_linear_distribution<RealType>& getPiecewiseLinearDistribution( std::size_t nw, RealType xmin, RealType xmax, UnaryOperation fw ) {
static std::piecewise_linear_distribution<RealType> dist( nw, xmin, xmax, fw );
return dist;
} // getPiecewiseLinearDistribution

}; // RandomDistribution

typedef RandomEngine RE;
typedef RandomDistribution RD;

#endif // RANDOM_GENERATOR_H

这是我上面的类的一次使用。如何使用它们也有多种选择。

main.cpp

// #include "Logger.h"
#include "RandomGenerator.h"
#include <isotream>
#include <sstream>

// ----------------------------------------------------------------------------
// main()
int main() {
// Logger log( "log.txt" );

std::ostringstream strStream;
strStream << "Random number generated Between [1,9] using default random engine & uniform int distribution is: " << std::endl;
//Logger::log( strStream, Logger::TYPE_CONSOLE );
std::cout << strStream.str();

std::uniform_int_distribution<unsigned> uid = RD::getUniformIntDistribution<unsigned>(1, 9);
// std::uniform_int_distribution<unsigned> uid( 1, 9 );
for ( unsigned int i = 1; i < 101; i++ ) {
std::ostringstream strStream;
unsigned val = uid( RE::getDefaultRandomEngine( RE::SeedType::USE_CHRONO_CLOCK, 14 ) );

strStream << i << " : " << val << std::endl;
//Logger::log( strStream, Logger::TYPE_CONSOLE );
std::cout << strStream.str();
}

std::cout << "\n";

for ( unsigned int i = 1; i < 101; i++ ) {
std::ostringstream strStream;
// Using the same distribution above but reseeding it with a different type of seeding method.
unsigned val = uid( RE::getDefaultRandomEngine( RE::SeedType::USE_RANDOM_DEVICE ) );

strStream << i << " : " << val << std::endl;
// Logger::log( strStream, Logger::TYPE_CONSOLE );
std::cout << strStream.str();
}

return 0;
} // main

我注释掉了属于我的记录器类的代码行,并将其替换为一个简单的 std::cout 调用。目前的设计方式是您只需创建一个分布类型的本地实例或成员实例,因为不需要创建实际随机引擎的本地实例code> 或 Seeding 对象,因为这一切都在静态存储中工作。我希望这对您有所帮助,因为它相当有效。

编辑 -- 这是另一个使用 Mersenne Twister 的示例,其真实分布在 [0,1] 之间,其中 50 个示例使用计时时钟播种:

int main() {

std::ostringstream strStream;
strStream << "Random number generated between [0.0, 1.0] \nusing mersenne & chrono clock for seeding:\n";
std::cout << strStream.str();

std::uniform_real_distribution<double> urd = RD::getUniformRealDistribution<double>( 0.0, 1.0 );
for ( unsigned i = 1; i <= 50; i++ ) {
std::ostringstream strStream;
double val = urd( RE::getMt19937( RE::SeedType::USE_CHRONO_CLOCK, 12 ) );
strStream << i << " : " << val << "\n";
std::cout << strStream.str();
}

return 0;
}

关于c++ - 在 .h 文件中声明正态分布生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46799778/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com