Re: generate random points on a line



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)
.



Relevant Pages

  • Re: error from mfilename
    ... typedef struct tagTRANSMITTER_CONFIGURATION ... PCIBIRD_API int InitializeBIRDSystem; ... Parameters Passed: USHORT sensorID, ...
    (comp.soft-sys.matlab)
  • [PATCH 1/2] Char: nozomi, Lindent the code
    ... +static const int nzdebug = 0; ... u8 port; ...
    (Linux-Kernel)
  • [LONG] help with old source code from book
    ... int cols, int magic_number); ... scale = 1.0; ... reads mesh data into a mesh structure * ...
    (comp.lang.c)
  • Re: access violation
    ... I didn't find any access violation on running your code in VC 6.0 compiler. ... typedef struct tagTIMESTAMP_STRUCT ... unsigned int fraction; ... > unsigned char u8; ...
    (microsoft.public.vc.language)
  • Re: Pointer
    ... > typedef struct { ... > unsigned int fitness; ... The general practice in C is not to use global variables, i.e. head, ...
    (comp.lang.c)