Generate points(x,y) on rectangle uniformly

1.8k views Asked by At

I would like to generate points(x,y) uniformly on rectangle. First You input minX and maxX and minY maxY and then you generate the (x,y) uniformly, The basic code is shown below is any better way to achive it? (I need it to monte carlo method to make a plot)

#include <iostream>
#include <random>
double drand(const double min = 0., const double max = 1.)
{
    return (max - min) * static_cast<double>(rand()) / static_cast<double>      (RAND_MAX)+min;
}
int main(int argc, char **argv)
{
    for(unsigned short int i=0;i<1000;++i)
    {
        std::cout << "x " << drand(minX, maxX) << std::endl;
        std::cout << "y " << drand(0., maxY) << std::endl;
    }
return 0;
}
2

There are 2 answers

3
duffymo On

Unless I misread your question, I would expect to see something like this Java code:

int nx = 10;
int ny = 10;
double x = xmin;
double dx = (xmax-xmin)/nx;
double dy = (ymax-ymin)/ny;
int id = 0;
for (int i = 0; i < nx; ++i) {
    double y = ymin;
    for (int j = 0; j < ny; ++j) {
        System.out.println(id, x, y);
        id++;
        y += dy;
    }
    x += dx;
}

I print these values, but you probably want to store them in a data structure that you can feed to your Monte Carlo simulation for evaluation.

2
David Hammen On

You're using rand(). Your barrier isn't all that high since almost anything is better than rand(). Since you apparently have C++11, why don't you use the much superior random number generators offered by C++11? For example,

#include <random>

double drand(const double min = 0., const double max = 1.)
{
   static std:: mt19937_64 mt_generator(std::random_device());
   static std::uniform_real_distribution<double> u_0_1(0.0, 1.0);

   return min + (max - min) * u_0_1(mt_generator);
}