0

I am trying to generate a set of points that I will connect to make polygon. The data has to be generated in a systematic way.

I am trying to generate the point set by randomly deriving radial coordinate r and evenly incrementing angular coordinate theta such that all the points are linked orderly without crossing with each other. I followed the correct formulas and I increment the angle but the data comes out negative because of sin and cos. I wanted to know if I'm doing this correctly.

struct Point2D {
    int x;
    int y;
};

Point2D poly[10];
int N = 80;

int x = (rand() % N + 1) * 5;
int y = (rand() % N + 1) * 5;
int r = sqrt(x*x + y*y);
int theta = int(atan ((float)y/(float)x) * 180 / PI);

cout << "x " << x << " y " << y << " r " << r << " theta " << theta << endl;

for (int i = 0; i < 10; i++) {

    Point2D p;
    p.x = x;
    p.y = y;
    poly[i] = p;

    theta += 20;
    x = r * sin(theta);
    y = r * cos(theta);

    cout << "x " << x << " y " << y << endl;

}
Rody Oldenhuis
  • 37,726
  • 7
  • 50
  • 96
Pete
  • 754
  • 2
  • 13
  • 27

1 Answers1

1

sin and cos return points on a unit circle centered around (0, 0), as paddy pointed out. To have no negative values in the points on your own polygon, you'll need to shift the origin of that circle. You're already changing its size, with r * sin(theta); you can accomplish a minimum translation with:

x = r * cos(theta) + r;
y = r * cos(theta) + r;

When I make this change to your program, I don't get negative values anymore.

Having said that, I suspect that you're not incrementing theta the way you intend. If you're trying to divide the circle into 10 equal angles, then theta should be a float or double and incremented like this:

theta += (2 * M_PI / 10);

theta is in radians, so 2 * M_PI is once around the unit circle.

Derek T. Jones
  • 1,800
  • 10
  • 18