5

I'm trying to write two functions for converting Cartesian coordinates to spherical coordinates and vice-versa. Here are the equations that I've used for the conversions (also could be found on this Wikipedia page):

enter image description here

And

enter image description here

Here is my spherical_to_cartesian function:

def spherical_to_cartesian(theta, phi):
    x = math.cos(phi) * math.sin(theta)
    y = math.sin(phi) * math.sin(theta)
    z = math.cos(theta)
    return x, y, z

Here is my cartesian_to_spherical function:

def cartesian_to_spherical(x, y, z):
    theta = math.atan2(math.sqrt(x ** 2 + y ** 2), z)
    phi = math.atan2(y, x) if x >= 0 else math.atan2(y, x) + math.pi
    return theta, phi

And, here is the driver code:

>>> t, p = 27.500, 7.500
>>> x, y, z = spherical_to_cartesian(t, p)
>>> print(f"Cartesian coordinates:\tx={x}\ty={y}\tz={z}")
Cartesian coordinates:  x=0.24238129061573832   y=0.6558871334524494    z=-0.7148869687796651
>>> theta, phi = cartesian_to_spherical(x, y, z)
>>> print(f"Spherical coordinates:\ttheta={theta}\tphi={phi}")
Spherical coordinates:  theta=2.367258771281654 phi=1.2168146928204135

I can't figure out why I'm getting different values for theta and phi than my initial values (the output values aren't even close to the input values). Did I make a mistake in my code which I can't see?

Farzin
  • 359
  • 1
  • 4
  • 21

2 Answers2

4

You seem to be giving your angles in degrees, while all trigonometric functions expect radians. Multiply degrees with math.pi/180 to get radians, and multiply radians with 180/math.pi to get degrees.

Dronir
  • 866
  • 7
  • 10
  • 1
    I remembered now that there are already two functions, `math.radians` and `math.degrees` which do the conversions, too. Looks a bit cleaner than multiplying by a constant. – Dronir Oct 07 '21 at 07:26
-1

The results are correct, but you should check their value using the modulo pi operation.

Trigonometric functions in the math package expect the input angles in radians. This means that your angles are larger than 2*pi and are equivalent to any other value obtained by adding or subtracting 2*pi (which also represents a full rotation in radians).

In particular you have that:

>>> 27.5 % (2*math.pi)
2.367258771281655

>>> 7.500 % (2*math.pi)
1.2168146928204138
Tonca
  • 122
  • 1
  • 11
  • OP's inputs are clearly degrees, and not radians with multiple rotations. Also, if they were, the functions would still work just fine. – ruohola Oct 06 '21 at 09:32
  • I just wanted to show that the conversions were working just fine. – Tonca Oct 06 '21 at 09:36
  • Angle units are not mentioned in the question so I would not take assumption. – Tonca Oct 06 '21 at 09:41
  • You're correct, but the degree/radian confusion seems probable enough to at least deserve a mention. – Dronir Oct 06 '21 at 10:01