1

I'm trying to find a way of choosing random lattice points in an x,y plane. It is suggested that I use the following code:

//////////////////////
// Pick random site //
////////////////////// 
int m=int(rand()*1.0/RAND_MAX*L*L);
int mx=m%L; //x coordinate of m site
int my=int(m*1.0/L); // y coordinate of m site

In other words: m is a random integer between 0 and L^2. The x coordinate is m mod L, which is a number between 0 and L. y is set as the closest integer to m/L, which is an integer between 0 and L.

It seems to work, but in L^2 runs, are we more likely to search one part of the x,y system than another? Could anyone explain why, and whether there is an alternative method for picking random coordinate points in on an x,y plane that sampled the space uniformly?

Checksum
  • 317
  • 1
  • 5
  • 18
Hector Crean
  • 322
  • 2
  • 7
  • 8
    Read this: [Generate random numbers uniformly over an entire range](https://stackoverflow.com/q/288739/691711) – zero298 Mar 01 '19 at 18:00
  • 6
    You'll probably find some better random number generators with control over distribution propabilities looking at the [standard c++ random number facilities](https://en.cppreference.com/w/cpp/numeric/random) than the primitive `std::rand()` function. – πάντα ῥεῖ Mar 01 '19 at 18:02
  • 1
    Well, other than the remarks in the previous comments, It depends on your definition of "uniformly sampled", I guess. Is [this](https://wandbox.org/permlink/l9Uad5cmCfMCvACq) close enough? – Bob__ Mar 01 '19 at 19:44
  • Many thanks team. @Bob__: really great of you to code that. Brilliantly visualised! – Hector Crean Mar 02 '19 at 01:33

1 Answers1

0

try to research pseudo generator Mersenne Twister, which is available from C++11. Hope this helps you.

Also look here for documentation.

Here is how you can use it for uniform distribution:

    int ran_num(const int start, const int stop)
    {
        random_device rd;
        mt19937 mt(rd());
        uniform_int_distribution dist(start, stop);

        return dist(mt);
   }

Hope this is somehow helpful!