1

As a part of a longer code, I get a quantity phi1 and phi2 (matrices of size 128x128) which are the arguments of a complex quantity. Now I define the following quantities in MATLAB:

alpha=phi1-phi2;
S1=cos(alpha);
S2=sin(alpha);
K=atan2(S2,S1);

Now, K should be equal to alpha. Therefore, the matrix B defined as:

B=K-alpha;

should be zero.But the result is coming out to be different. Though several elements of B are zero, a lot of them have the value 6.2832 (i.e 2pi). Why this could be happening?

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
A Khan
  • 85
  • 8
  • Actually, phi1 and phi2 are angles evaluated in MATLAB. Hence their ranges lie between -pi and pi. when I evaluate alpha the range of the values lie no more between -pi and pi. Hence, atan2 is not giving the exact alpha value. But the thing is that I want exact alpha value, because there is another equation giving beta=phi1+phi2. And my main aim is to evaluate phi1 by deriving alpha from S1 and S2 and the beta equation. For that I want exact alpha value, as it is. But no matter what I try I am not able to retrieve alpha exactly. Can anyone please suggest something? – A Khan Apr 19 '17 at 09:50

1 Answers1

2

The atan2 function always returns values between -pi and pi. So, for example, for alpha = 4 your code

S1=cos(alpha);
S2=sin(alpha);
K=atan2(S2,S1)

gives

K =
  -2.2832

which is alpha but moved (modulo 2*pi) to the interval between -pi and pi.

This shouldn't be a problem, because two angles that differ by 2*pi are actually the same. So a possible solution is to compare the angles by doing the subtraction modulo 2*pi:

>> mod(alpha-K, 2*pi)
ans =
     0

Note also that, due to numerical rounding errors, you should not rely on the difference modulo 2*pi being exactly 0. Instead, compare its absolute value to a given tolerance.

Community
  • 1
  • 1
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147