cmathfloating-pointintervalsmodulo

Modulus to limit latitude and longitude values


I have doubles that represent latitudes and longitudes.
I can easily limit longitudes to (-180.0, 180.0] with the following function.

double limitLon(double lon)
{
  return fmod(lon - 180.0, 360.0) + 180.0;
}

This works because one end is exclusive and the other is inclusive. fmod includes 0 but not -360.0.

Can anyone think of an elegant method for latitude?
The required interval is [-90.0, 90.0]. A closed form solution would be best, i.e. no loop. I think fmod() is probably a non-starter because both ends are inclusive now.

Edit: As was pointed out, one can't go to 91 degrees latitude anyway. Technically 91 should map to 89.0. Oh boy, that changes things.


Solution

  • How about using the sin and inverse functions?

    asin(sin((lat/180.0)*3.14159265)) * (180.0/3.14159265);