I believe this is a correct implementation of atan2 using atan (doesn't handle infinities, though):
float my_atan2(float y, float x)
{
if(x == 0) // might also want to use fabs(x) < 1e-6 or something like that
{
if(y > 0)
return M_PI_2;
else
return -M_PI_2;
}
else if(x > 0)
{
return atan(y/x);
}
else
{
// x < 0
if(y > 0)
return M_PI + atan(y/x);
else
return -M_PI + atan(y/x);
}
}
Test harness:
int main()
{
for(int i = -360; i <= 360; i++)
{
float x = cos(i / 180.0 * M_PI);
float y = sin(i / 180.0 * M_PI);
float good = atan2(y, x);
float mine = my_atan2(y, x);
if(fabs(good - mine) > 1e-6)
{
printf("%d %f %f %f %f\n", i, x, y, good, mine);
}
}
}