Jpoor
Jpoor

Reputation: 1

Random number generator function in class

Hello I am trying to create a function that will give me a random number and then return it as a protected int in my class that will be inherited. what I am trying to is create a random number (0,1) and then pass it to the inherited class GBM. In that class I need to use it for a monte carlo simulation. How can I create a random number that will be inherited?

header file

#pragma once

#include <iostream>
#include <random>
#include <chrono>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::default_random_engine;
using std::normal_distribution;
using std::vector;


class option
{
private:
    float mean_ = 0.0;
    float std_ = 1.0;

protected:
    float rnum;
    void RANDOM();

public:
    option();
    virtual float get_rnum() = 0;
    virtual void simulation() = 0;
    virtual ~option() {};
};

class GBM : public option
{
public:
    GBM();
    virtual float get_rnum();
    virtual void simulation();
    virtual ~GBM () {}
};

cpp file

#include "Option.h"
void option::RANDOM()
{
    const int N = 500000;
    unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
    std::default_random_engine generator(seed);
    std::normal_distribution<float> RAND(mean_, std_);

    for (int i = 0; i <= N; i++)
    {
        rnum = RAND(generator);
    }
}


option::option()
{
}

GBM::GBM()
{
}

float GBM::get_rnum()
{
    float k;
    k = rnum;

    return (k);
}

Upvotes: 0

Views: 2579

Answers (2)

Jpoor
Jpoor

Reputation: 1

so something like this:

  void option::RANDOM()
{
    unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
    static std::mt19937 generator(seed);
    std::normal_distribution<float> RAND(mean_, std_);
    rnum = RAND(generator);

}


option::option()
{
    float rnum;
}

Upvotes: 0

D&#250;thomhas
D&#250;thomhas

Reputation: 10123

Random number generators work best when they exist for a long time. However, your RANDOM() method creates, seeds, and uses a new RNG every time it is called.

If you want your option object to stand-in as a RNG, create the actual RNG and seed it in the constructor, just once, and then extract a random number from it using your RANDOM() method.

Remember, create your RNG once. Seed it once, when you create it. Make sure it exists for a long time. BTW, you should also discard() at least a thousand numbers to warm it up.

Unrelatedly, ALL_CAPS tells C and C++ people you are using a MACRO -- but you aren't, actually.

Hope this helps.

Upvotes: 1

Related Questions