A Khan
A Khan

Reputation: 85

tan inverse in matlab not giving correct values

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?

Upvotes: 1

Views: 571

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112679

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.

Upvotes: 2

Related Questions