lundi 29 juin 2015

linear distribution in c++ using rand()

I am writing a function that generates n random points (x, y) such that xmin < x < xmax and ymin < y < ymax. This is easy to do with uniform distribution using rand().

int points[n][2];
for (int i = 0; i < n; i++) {
    points[i][0] = rand() % (xmax - xmin) + xmin;
    points[i][1] = rand() % (ymax - ymin) + ymin;
}

However, I would like to control the distribution so that the probability of each point having a given x or y value is px = (px2 * (x - xmin) + px1 * (xmax - x)) / (xmax - xmin) or py = (py2 * (y - ymin) + py1 * (ymax - y)) / (xmax - xmin), respectively. In other words, a linear distribution across the rectangle in each dimension.

I can fake this by partitioning the rectangle into sufficiently small discrete rectangles and using the algorithm above for each one, with n proportional to the average probability across that smaller rectangle. However, I would prefer to apply a continuous distribution across the entire rectangle. Can this be done, either using rand() or with another approach?




Aucun commentaire:

Enregistrer un commentaire