Matlab 除以 0:Inf 或 -Inf

Matlab division by 0: Inf or -Inf

我不明白为什么在以下两种情况下除以 0 会产生不同的结果。 amort 是一个计算常数摊销时间表的函数。我们现在唯一关心的是A的最后一个元素正好是0。

amort = @(r,M) ((1+r).^(0:M)' - (1+r).^M) ./ (1-(1+r).^M)

A = amort(0.03, 20);

>> A(end)==0
ans =
     1

看起来奇怪的是:

>> 1/0
ans =
   Inf
>> 1/A(end)
ans =
  -Inf

然而

>> sign(A(end))
ans =
     0
>> 1/abs(A(end))
ans =
   Inf

这怎么可能,为什么?有没有什么隐藏的"sign"?

A(end) 实际上设置了符号位(即负零)。尝试使用 num2hex 查看十六进制表示:

>> a = -0
a =
     0    % Note the sign isn't displayed

>> num2hex(A(end))
ans =
8000000000000000

>> num2hex(a)
ans =
8000000000000000  % Same as above

>> num2hex(0)
ans =
0000000000000000  % All zeroes

>> 1/a
ans =
  -Inf

请注意 -0 显示为 0,但实际上它的符号位已设置。因此 -Inf 结果。

另请注意 sign 函数的解释(重点是我的):

For each element of X, sign(X) returns 1 if the element is greater than zero, 0 if it equals zero and -1 if it is less than zero.

因为 -0 不小于零,而是等于 0sign returns 0.