I have a class (randomHandler) that contains several functions for calling certain types of random numbers (i.e. randomNormal(mu, sigma), randomUniform(), randomOnSphere(), etc) based on a mersenne twister generator.
A second class (aSubroutine) creates a randomHandler object and then uses that as it's source for random numbers throughout the subroutine. I need the subroutine to iteratively call functions that are passed the random object, but each call attempted currently returns repeated randoms.
My guess is that this is due to a miss understanding on my part to how the random generator moves to the next random number in the "list", and how the function going out of scope causes the random number "index" to be reset to what is was before it was passed to the function.
What is the proper way to handle the passing of an object of random generating functions to a function?
Some code for reference. Apologies for the convoluted nature of the layers but I am aiming to make it representative without context.
#include ...
int main()
{
randomHandler randobj = randomHandler();
iterSubroutine itersub = iterSubroutine();
return 0;
}
//------randomHandler.h-----
class randomHandler
{
private:
mtHandler generator = mtHandler();
public:
void randomHandler();
void randomHandler(time);
~randomHandler();
double randomUniform();
double randomNormal(double mu, double sigma);
double randomOnSphere();
}
//------randomHandler.cpp-----
void randomHandler::randomHandler()
{
std::cout << generator.mtSeed << std::endl;
}
double randomHandler::randomUniform()
{
// I acknowledge there are better ways to handle random
// generation than the following.
std::uniform_real_distribution<double> disly(0.0, 1.0);
return disly(jb_generator.m_mt);
}
//other functions below
...
//------mtHandler.h-----
class mtHandler
{
public:
mtHandler();
~mtHandler();
std::mt19937 m_mt;
unsigned int m_mtseed;
};
//------mtHandler.cpp-----
mtHandler::mtHandler() : m_mt((std::random_device())())
{
m_mtseed = (std::random_device())();
m_mt.seed(m_mtseed);
}
mtHandler::~mtHandler()
{
}
//------iterSubroutine.h-----
class iterSubroutine
{
public:
void iterSubroutine();
void iterSubroutine(randomHandler randobj);
void function(randomHandler randobj);
~iterSubroutine();
}
//------iterSubroutine.cpp-----
iterSubroutine::iterSubroutine(randomHandler randobj)
{
// This loop repeats the same number
for (int i=0;i<10;i++)
{
function(randobj);
}
// This loop generates different numbers
for (int i=0;i<10;i++)
{
std::cout << randobj.randomUniform() << std::endl;
}
}
void iterSubroutine::function(randobj)
{
std::cout << randobj.randomUniform() << std::endl;
}
~iterSubroutine()
{
}
Aucun commentaire:
Enregistrer un commentaire