MATLAB:为什么我使用 acos 得到一个复数?
MATLAB: Why do I get a complex number using acos?
设K=5
,而alpha = 1:0.5:10
.
我的代码是:
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
为什么我返回变量 theta
作为 complex double
?
cos
函数如下所示:
图片来源:Wikipedia, Trigonometric functions
如您所见,余弦 永远不会 高于 1
或低于 -1
。您正在使用 acos
,它是余弦的反函数。你基本上是在问这个问题:"What value for x
makes cos(x)
return my given y
value?"
现在,对于 h=3
,您的代码创建了 cos_theta
,它们在 下方 -1
。从图中可以看出,不可能用实数达到这样的值。但是,复数的余弦 可以 达到高于 1
和低于 -1
的值。 MATLAB 正确地识别出不存在真正的解决方案,但存在复杂的解决方案 - 因此它 returns 复杂的角度。对于 h=1
和 h=2
,cos_theta
的表现很好并且比 -1
小,所以结果是真实的。
PS: For-loops 是 bad/slow。您可以通过使 h
成为列向量而不是行向量(通过使用 .'
转置它),然后使用 bsxfun
(在 "old" MATLAB 版本) 或在 R2016 或更高版本中使用 built-in 广播。
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);
设K=5
,而alpha = 1:0.5:10
.
我的代码是:
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
为什么我返回变量 theta
作为 complex double
?
cos
函数如下所示:
图片来源:Wikipedia, Trigonometric functions
如您所见,余弦 永远不会 高于 1
或低于 -1
。您正在使用 acos
,它是余弦的反函数。你基本上是在问这个问题:"What value for x
makes cos(x)
return my given y
value?"
现在,对于 h=3
,您的代码创建了 cos_theta
,它们在 下方 -1
。从图中可以看出,不可能用实数达到这样的值。但是,复数的余弦 可以 达到高于 1
和低于 -1
的值。 MATLAB 正确地识别出不存在真正的解决方案,但存在复杂的解决方案 - 因此它 returns 复杂的角度。对于 h=1
和 h=2
,cos_theta
的表现很好并且比 -1
小,所以结果是真实的。
PS: For-loops 是 bad/slow。您可以通过使 h
成为列向量而不是行向量(通过使用 .'
转置它),然后使用 bsxfun
(在 "old" MATLAB 版本) 或在 R2016 或更高版本中使用 built-in 广播。
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);