Friday, July 06, 2012

[ftodcsqx] Cartesian to Polar coordinates in C

Converting between cartesian and polar coordinates (radians) involves some not very frequently used functions for efficiency and to avoid underflow or overflow. All of these functions are quite hairy underneath the covers.

#ifndef _GNU_SOURCE
//needed for sincos
#define _GNU_SOURCE
#endif
#include <math.h>

void cartesian_to_polar(const double x, const double y, double*r, double*theta){ *r=hypot(x,y); *theta=atan2(y,x); }

void polar_to_cartesian(const double r, const double theta, double*x, double*y){ sincos(theta,y,x); *x*=r; *y*=r; }

Also exist float versions: hypotf atan2f sincosf.

Also consider the C99 complex type and functions cabs carg cimag creal. Can the dual "multiply by r"s in polar_to_cartesian be vectorized?

No comments :