Search code examples
coordinatescoordinate-systemscoordinate-transformationpolar-coordinatesspherical-coordinate

Spherical coordinate conversion gives wrong polar angle


This is my code for conversion

double xDif = point.getX() - origin.getX();
double yDif = point.getY() - origin.getY();
double zDif = point.getZ() - origin.getZ();
double radius = Math.sqrt((xDif * xDif) + (yDif * yDif) + (zDif * zDif));
double azimuthalAng = Math.acos(zDif / radius);
double polarAng = Math.atan(yDif / xDif);
return new SpherePoint(radius, azimuthalAng, polarAng);

origin = 400, 400, 400

point = 100, 100, 100

so, vector = -300, -300, -300

Math.toDegrees();

my conversion algorithm gave the same azimuthal angle and radius as this website http://keisan.casio.com/exec/system/1359533867

but the website gave me a polar angle of -135, while my algorithm gave 45

can anyone tell me what's wrong?


Solution

  • atan() cannot return the correct quadrant for the angle. You are passing it yDif / xDif, which is -300 / -300, or 1, so it will give the same value as it would for 300 / 300.

    Most languages have a function atan2(yDif, xDif) which will give the correct value. It will also deal with the case where xDif is 0.