11
\$\begingroup\$

I've googled this using a lot of keyword combinations, but to my great surprise I could not find an algorithm for constructing a regular, n-sided polygon into a given circle, i.e., finding the coordinates for the n corner points. All I could find were instructions how to do it by physical compass and straightedge, or interactive browser plug-ins without source.

So where could I find such an algorithm?

\$\endgroup\$
1
  • 2
    \$\begingroup\$ Let me restore your faith in the Google. ;-) Fourth hit for "algorithm regular polygon": gamedev.net/topic/… "Then, using basic trigonometry, chose n points spaced equidistantly around the circumference of the circle (ie - if n is 3, chose 3 points on the circumference that are 120 degrees apart from one another)." Which is exactly what Kevin's code does. \$\endgroup\$
    – Eric
    Commented May 24, 2012 at 14:26

1 Answer 1

16
\$\begingroup\$

To build the list of the vertices of a regular, n-sided polygon inscribed into a given circle, pointy on the right sided. Where (xOffset,yOffset) is the center of the circle.

With i going from 0 to n-1 inclusive:

pointX[i] = ( cos( i / n * 2 * PI ) * radius ) + xOffset;
pointY[i] = ( sin( i / n * 2 * PI ) * radius ) + yOffset;

Edit: As Lars Viklund mentioned in the comments, this is only safe in languages like javascript in which integer division returns a floating point number rather than a integer. In other languages you should first cast i to a float.

\$\endgroup\$
4
  • 3
    \$\begingroup\$ Beware the trap of integral division in i/n in languages where dividing integers yields an integer. \$\endgroup\$ Commented May 24, 2012 at 14:11
  • \$\begingroup\$ Aah a very good point, I'll add that caveat in the answer. \$\endgroup\$
    – Elva
    Commented May 24, 2012 at 14:24
  • \$\begingroup\$ This goes without saying, but you'll also want to guard against the case where n * 2 * PI == 0 or you'll have one unhappy polygon :(. \$\endgroup\$ Commented May 25, 2012 at 22:39
  • \$\begingroup\$ Barring weird overflows the only n with n * 2 * PI == 0 I can think of is 0, which as far as I know is undefined, same as i / 0. So no problem right? :) \$\endgroup\$
    – Elva
    Commented May 26, 2012 at 8:42

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .