Skip to content

Instantly share code, notes, and snippets.

@njamescouk
Last active April 11, 2018 15:49
Show Gist options
  • Save njamescouk/be05dc223776637d6396710879ca5973 to your computer and use it in GitHub Desktop.
Save njamescouk/be05dc223776637d6396710879ca5973 to your computer and use it in GitHub Desktop.
get angle of position vector wrt to initial line.
/*
angle.cpp
compute angle given sine and cosine
*/
#include <cmath>
#include <cstdio>
#include <cassert>
#include <cstdlib>
int quadrant(double x, double y);
void usage(FILE *fp);
#define PI 3.14159265358979323846
int main(int argc, char *argv[])
{
if (argc == 1)
{
usage(stderr);
return 1;
}
if (argv[1][0] == '-' && argv[1][1] == 'h')
{
usage(stdout);
return 0;
}
if (argc != 3)
{
usage(stderr);
return 1;
}
char *endptr;
double x = strtod(argv[1], &endptr);
double y = strtod(argv[2], &endptr);
double diag = _hypot(x, y);
if (diag == 0)
{
fprintf(stderr, "hypotenuse has zero length\n");
return 2;
}
double xHat = x/diag;
double yHat = y/diag;
int quad = quadrant(xHat, yHat);
switch(quad)
{
case 1:
printf("%f\n", asin(yHat));
break;
case 2:
printf("%f\n", acos(xHat));
break;
case 3:
printf("%f\n", 2*PI - acos(xHat));
break;
case 4:
printf("%f\n", 2*PI + asin(yHat));
break;
}
assert(false);
return 0;
}
int quadrant(double x, double y)
{
if (y >= 0)
{
if (x >= 0)
return 1;
if (x < 0)
return 2;
}
else if (y < 0)
{
if (x < 0)
return 3;
if (x >= 0)
return 4;
}
assert(false);
return 42;
}
void usage(FILE *fp)
{
fprintf(fp,
"usage: angle x_coordinate y_coordinate\n"
"prints the angle between (x, y) and the initial line\n");
}
@njamescouk
Copy link
Author

get angle between point and initial line in [0,2pi]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment