Re: generate random points on a line
- From: Martin Ambuhl <mambuhl@xxxxxxxxxxxxx>
- Date: Fri, 29 Apr 2005 03:40:45 GMT
Marc Dansereau wrote:
Hi all,
I wonder what is the most efficient way to generate random point on a line defined by 2 double points (x0,y0) and (x1,y1).
Here is the pseudocode of my method :
for each point { dx=x1-x0 dy=y1-y1
if dx != 0 { m=dy/dx b = y0-m*x0 x = (rand()%(int)dx)+x0 y = m* x + b printf("(%f, %f) is a random point on the line", x, y); } else { x = x0 y = (rand() %(int)dy)+y0 } }
There is probably a problem with the rounding of dy and dx ... There is probably a better way to do this, but I can't figure which ?
#include <stdio.h> #include <stdlib.h> #include <time.h>
typedef struct
{
double x, y;
} pt;pt randompt(pt a, pt b)
{
pt c;
c.x = a.x + (b.x - a.x) * rand() / (1. + RAND_MAX);
c.y = a.y + (c.x - a.x) * (a.y - b.y) / (a.x - b.x);
return c;
}int main(void)
{
pt p1 = { 1, 1 }, p2 = { 2, 3 }, p3;
int i;
const int npts = 10;
srand((unsigned) time(0));
printf("Here are %d randomly chosen points on the line\n"
"from (%g,%g) to (%g,%g)\n", npts, p1.x, p1.y, p2.x, p2.y);
for (i = 0; i < npts; i++) {
p3 = randompt(p1, p2);
printf("%2d: (%g,%g)\n", i + 1, p3.x, p3.y);
}
return 0;
}Here are 10 randomly chosen points on the line from (1,1) to (2,3) 1: (1.38438,1.76876) 2: (1.46981,1.93962) 3: (1.96502,2.93003) 4: (1.68285,2.3657) 5: (1.91771,2.83543) 6: (1.77233,2.54467) 7: (1.88148,2.76296) 8: (1.26106,1.52211) 9: (1.77445,2.5489) 10: (1.43061,1.86122) .
- References:
- generate random points on a line
- From: Marc Dansereau
- generate random points on a line
- Prev by Date: Re: How is strlen implemented?
- Next by Date: Count maximum contiguous set bits in an integer .
- Previous by thread: Re: generate random points on a line
- Next by thread: Count maximum contiguous set bits in an integer .
- Index(es):
Relevant Pages
|