Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a set of points that are equidistant from each other and lie on a circle

Tags:

c

geometry

I am trying to generate an array of n points that are equidistant from each other and lie on a circle in C. Basically, I need to be able to pass a function the number of points that I would like to generate and get back an array of points.

like image 415
Shane M. Pelletier Avatar asked Dec 13 '22 13:12

Shane M. Pelletier


2 Answers

It's been a really long time since I've done C/C++, so I've had a stab at this more to see how I got on with it, but here's some code that will calculate the points for you. (It's a VS2010 console application)

// CirclePoints.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "stdio.h"
#include "math.h"

int _tmain()
{
    int points = 8;
    double radius = 100;

    double step = ((3.14159265 * 2) / points);
    double x, y, current = 0;
    for (int i = 0; i < points; i++)
    {
        x = sin(current) * radius;
        y = cos(current) * radius;

        printf("point: %d x:%lf y:%lf\n", i, x, y);

        current += step;
    }

    return 0;
}
like image 115
Mike Goatly Avatar answered May 20 '23 01:05

Mike Goatly


Try something like this:

void make_circle(float *output, size_t num, float radius)
{
  size_t i;

  for(i = 0; i < num; i++)
  {
    const float angle = 2 * M_PI * i / num;
    *output++ = radius * cos(angle);
    *output++ = radius * sin(angle);
  }
}

This is untested, there might be an off-by-one hiding in the angle step calculation but it should be close.

This assumes I understood the question correctly, of course.

UPDATE: Redid the angle computation to not be incrementing, to reduce float precision loss due to repeated addition.

like image 33
unwind Avatar answered May 20 '23 03:05

unwind