Search code examples
matlabroundingprecisiondegreesradians

Why do the outcomes of converting an angle with deg2rad and by multiplying with pi/180 differ?


I'm using the Matlab function deg2rad to convert angles from degrees to radians (obviously). I use them for angles alpha and beta, which are in turn used to interpolate some tabular data f(alpha, beta), which is with respect to alpha and beta in degrees. For my purposes, I use them in radians, such that I have to convert back and forth every now and then.

Now, I found that - as opposed to using f(pi/180*alpha, pi/180*beta) - whenever I interpolate using f(deg2rad(alpha), deg2rad(beta)), the interpolation is outside the interpolation area at the boundaries. I.e., the interpolation boundaries are at alpha = [-4, 4], beta = [-3, 3] and interpolating along those boundaries gives me NaN when using deg2rad. This thus looks like some kind of round-off or machine precision error.

Now, as a MWE, suppose I want to check deg2rad(-3) == -3*pi/180, this gives me:

>> deg2rad(-3) == -3*pi/180
ans =
  logical
   0

My questions are the following:

  1. How do I prevent this behaviour, where using deg2rad is basically not useful for me when operating near the edges of the interpolation area?
  2. What does the deg2rad function do, other than multiplying with pi/180?

Thanks in advance.

P.s. It is even stranger than I thought, because with different angles, it does work:

>> deg2rad(2) == 2*pi/180
ans =
  logical
   1

Solution

  • Your question is answered by typing edit deg2rad into MATLAB. It computes:

    angleInRadians = (pi/180) * angleInDegrees;
    

    Of course, the order of operation differs between your version ((a*pi)/180) and MATLAB's (a*(pi/180)). This different order causes rounding errors to differ.

    If rounding errors cause a problem in your function, your function is unstable and needs to be fixed.