lundi 3 décembre 2018

C++ question regarding random number generator and drand48()

Hi I am trying to avoid having to use any methods from the rand library, and instead would like to use only the methods from the random library but I am running into an issue regarding drand48(). Essentially, its function (as far as I know) is to randomly choose a number between [-1, 1]. But when I substitute my method using methods from the random library, it is not getting the same output.

Here is the original code with drand48() and srand48():

#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <math.h>

using namespace std;

main () {
     int N;             // N dimensions
     double vol;
     double xin;
     double xout;
     double hit;

     srand48(time(NULL));

     cout << "Enter a number for N dimensions: " << endl;
     cin >> N;
     double n_vol = pow(M_PI, double(N/2.0)) / exp(lgamma(double(N/2.0)+1.0));  // volume eq. for N-spheres

     for (int i = 0; i < 10000; i++) {
         double r = 0;
         for (int j = 0; j < N; j++) {
             double x = 2*(drand48()-.5);
             r += x*x;
         }
         if (sqrt(r) < 1) {
             hit += 1;
         }
     }

     vol = ( pow(2,N) * hit ) / 10000;
     cout << "Volume of a " << N << "-sphere: " << vol << endl;
     cout << "Actual volume: " << n_vol << endl;
     cout << "Fractional error: " << fabs( n_vol - vol) << endl

;

And here is my implementation using the random methods:

#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <math.h>
#include <random>

using namespace std;

int main () {
        int dim;
        double vol;
        //double xin;
        //double xout;
        double hit;
        int trials;
        int i, j;
        double sum;
        double pt;

        //srand48(time(NULL));
        //random_device dev;
        default_random_engine e;
        e.seed(32767);
        uniform_int_distribution<unsigned> u(0,9);

        cout << "Enter the number of dimensions: " << endl;
        cin >> dim;
        trials = 10000 * dim;
        double n_vol = pow(M_PI, double(dim/2.0)) / exp(lgamma(double(dim/2.0)+1.0));

        for (i = 0; i < trials; i++) {
                sum = 0;
                for (j = 0; j < dim; j++) {
                        pt = 2*(u(e)-.5);
                        printf("%d", pt);
                        sum += pt*pt;
                }
                if (sqrt(sum) < 1) {
                        hit += 1;
                }
         }

     vol = ( pow(2,dim) * hit ) / trials;
     cout << "Volume of a " << dim << "-sphere: " << vol << endl;
     cout << "Actual volume: " << n_vol << endl;
     cout << "Fractional error: " << fabs( n_vol - vol) << endl;

     return 0;
}

How do fix it so that I get the same output (which should be fractional error close to 0) but using random methods instead of the less reliable rand?




Aucun commentaire:

Enregistrer un commentaire