views:

304

answers:

3

I need to convert rectangular coordinates to polar coordinates. Can you recommend a library that I can use, I would rather not have to write this myself.

This is used for making sense of metadata included in astronomy image files.

+1  A: 

I am pretty sure the standard library already has this. If there are imaginary number types, they do precisely this (real = x, imag = y, arg(val) = angle, abs(val) = radius). Using the math library (atan2, sin, cos and sqrt) isn't that difficult either.

Tronic
+1  A: 

isn't this just like 2 functions? surely you could just search for it in any language and convert it yourself.

here is my code to do rectangular -> polar (the other way is very easy) in c++

Vector3 C2P (const Vector3 &v)
{
        float PI=3.14159260f;
        Vector3 polar;
       polar.x = v.Length();

       if (v.z > 0.0f) {
              polar.y = (float) atan ( v.z/sqrt (v.x * v.x + v.y * v.y));
       }
       else if (v.z < 0.0f) {
               polar.y = (float) -atan (sqrt (v.x * v.x + v.y * v.y) / v.z);
        }
        else {

                polar.y = 0.0;
        }


        if (v.x > 0.0f) {
                polar.z = (float) atan (v.y / v.x);
        }
        else if (v.x < 0.0f) {
               polar.z = (float) atan (v.y / v.x) + PI;
        }
        else if (v.y > 0) {
                polar.z = PI * 0.5f;
      }
     else {
              polar.z = -PI * 0.5f;
        }
       //polar.z=(polar.z/M_PI)*180;
       //polar.y=(polar.y/M_PI)*180;
       return polar;
}

note the result is x = length, y = angle1 z = angle2, in radians.

EDIT: by my code, I mean some code that I stole from somewhere and used like once.

matt
Crappy implementation. You should be using atan2 instead of atan to avoid the if-elses.
Tronic
+1  A: 

What you are asking for is a Map Projection Library. One of the most popular open source libraries are PROJ.4 and there is one Java Implementation of it.

You have to decide what projection you want to use. They have different properties. Mercator is common and is the one that Google Maps is using. The disadvantage with Mercator is that you can not use it around the arcitc poles.

Jonas