lundi 22 février 2021

Uniform_real_distribution between 0.0 and 1.0 generates extremely low numbers in C++ always close to 0

Inside a class, I am trying to implement a method that generates a random number which would end up being a property of the class. I am calling the method randomPropertyGenerator inside the object constructor.

My minimum code for reproducing the issue looks like this

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <random>
using namespace std;

class Object {
    public:
        double randomProp;
        double randomPropGen(double a, double b);
        Object() {
            double randomProp = randomPropGen(0.0, 1.0);
        }
};

double Object::randomPropGen(double min, double max){
    std::uniform_real_distribution<double> distribution(min, max);
    std::random_device rd;
    std::default_random_engine generator(rd());
    return distribution(generator);
}

int main(int argc, char *argv[]){
    std::uniform_real_distribution<double> distribution(0.0, 1.0);
    std::random_device rd;
    std::default_random_engine generator(rd());
    
    Object o = Object();
    for (int i = 0; i < 10; i++){
        double randomProp2 = distribution(generator);
        cout << "This is randomProp from object " << o.randomProp << endl;
        cout << "This is randomProp2 inside main " << randomProp2 << endl;
        cout << "\n" << endl;
    }
    return 0;
}

When I compile the code and run it, I am getting the following results:

This is randomProp from object 8.35785e-318
This is randomProp2 inside main 0.688014


This is randomProp from object 8.35785e-318
This is randomProp2 inside main 0.263372


This is randomProp from object 8.35785e-318
This is randomProp2 inside main 0.689736


This is randomProp from object 8.35785e-318
This is randomProp2 inside main 0.392283


This is randomProp from object 8.35785e-318
This is randomProp2 inside main 0.96836


This is randomProp from object 8.35785e-318
This is randomProp2 inside main 0.401998


This is randomProp from object 8.35785e-318
This is randomProp2 inside main 0.91537


This is randomProp from object 8.35785e-318
This is randomProp2 inside main 0.608586


This is randomProp from object 8.35785e-318
This is randomProp2 inside main 0.168815


This is randomProp from object 8.35785e-318
This is randomProp2 inside main 0.631994

As you can see the randomProp when generated inside the method of my class is always the same and seems to be always extremely close to 0, whereas the randomProp generated in the main class makes more sense. Can someone tell me what I am doing wrong and how I can fix the method? Thanks for your help!




Aucun commentaire:

Enregistrer un commentaire