clamp Spherical coordinates to latitude/longitude

Solution 1:

If you want efficiency, using $\text{arccos}(\cos \phi)$ is like driving 5 miles south to the ring-freeway, following it around to the north side of town, and driving another 5 miles south to visit the second house up the block from where you started. Similarly for $\text{atan2}$. You would be hard-pressed to come up with a more in-efficient solution.

Seriously - computers directly add, subtract, multiply, and divide. Anything else takes multiple steps to calculate - usually many such steps. It used to be that even multiplying and dividing required multiple steps, but then chip technology improved until the whole logic could be performed in one step. And yes, on the most advanced chips, some functions - square rooting in particular - are now incorporated into a single operation. But even if the trig functions were all incorporated, why would you bother when the problem has a much more simple computation?

A simple algorithm takes care of it:

ToLatitudeLongitude(phi, theta)    
   phi = mod(phi, 2*pi)
   theta = mod(theta, 2*pi)
   if (phi > pi) 
      phi = 2*pi - phi
      if (theta < pi) 
         theta = theta + pi
      else 
         theta = theta - pi

   return (phi, theta)