Search code examples
matlabtrigonometryinverse

MATLAB: Why do I get a complex number using acos?


Let K=5, while alpha = 1:0.5:10.

My code is:

cos_theta_0 = -1./(2.*alpha)+sqrt(1.+1./(4.*alpha.^2));
theta_0 = acos(cos_theta_0);

 for h = 1:(K-2)
     cos_theta(h,:)= cos_theta_0 - h.*log(2);
     theta(h,:)= acos(cos_theta(h,:));
 end 

Why do I get back the variable theta as a complex double?


Solution

  • The cos function looks like this:

    Plot of sine and cosine
    Image Source: Wikipedia, Trigonometric functions

    As you can clearly see, the cosine never goes above 1 or below -1. You are working with the acos, which is the inverse function of the cosine. You basically ask the question: "What value for x makes cos(x) return my given y value?"

    Now, for h=3, your code creates cos_theta's which are below -1. As you can see from the graph, it is not possible to reach such values with real numbers. However, the cosine of a complex number can reach values above 1 and below -1. MATLAB correctly recognizes that no real solution exists, but complex solutions do - so it returns complex angles as a result. For h=1 and h=2, the cos_theta's behave nicely and are smaller than -1, so the results are real.

    PS: For-loops are bad/slow. You can drop this one by making h a column vector instead of a row vector (by transposing it using .'), and then using either bsxfun (in "old" MATLAB versions) or use the built-in broadcasting in R2016 or newer.

    h = (1:K-2).';
    cos_theta = bsxfun(@minus, cos_theta_0 , h*log(2));    % For older than R2016
    cos_theta = cos_theta_0 - h*log(2);                    % For newer than R2016 
    theta = acos(cos_theta);