2017-01-20 22 views
1

K=5,而alpha = 1:0.5:10MATLAB:爲什麼我用acos得到一個複數?

我的代碼是:

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 

爲什麼我找回變量thetacomplex double

+0

什麼是'alpha'的* actual *值。 – Suever

+2

因爲,正如Matlab的良好文檔告訴你的那樣,你已經在'[-1,1]'之外給'acos'一個參數? –

+0

'alpha'是一個由1到10的19值組成的數組,具有0.5 -step @Suever – ElenaPhys

回答

1

cos功能如下:

Plot of sine and cosine
圖片來源:Wikipedia, Trigonometric functions

正如你可以清楚地看到,餘弦從未進入上述1或低於-1。您正在使用acos,這是餘弦的反函數。你基本上問的問題:「x什麼值使得cos(x)返回我給定的y值?」

現在,h=3,您的代碼創建cos_theta的這是低於-1。正如你從圖表中看到的那樣,用而不是可能用實數達到這樣的值。但是,複數的餘弦值可能會達到1以上且低於-1的值。 MATLAB正確地認識到沒有真正的解決方案存在,但複雜的解決方案 - 因此它返回複雜的角度。對於h=1h=2cos_theta的表現很好,並且小於-1,所以結果是真實的。

PS: For-loops壞/慢。你可以通過使用h而不是行矢量(通過使用.'轉置它),然後使用bsxfun(在「舊」MATLAB版本中)或使用R2016或更新版本中的內置廣播來放棄這個。

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); 
相關問題