Search code examples
matlabdivisioninfinitezerodivide-by-zero

Matlab division by 0: Inf or -Inf


I cannot figure out why division by 0 gives different results in the following two cases. amort is a function that calculates a constant amortization schedule. The only thing we care about now is that the last element of A is exactly 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

What looks strange is the following:

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

However

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

How is this possible and why? Is there some kind of hidden "sign"?


Solution

  • A(end) actually has it's sign bit set (i.e. it is negative zero). Try using num2hex to see the hex representation:

    >> 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
    

    Notice that a -0 is displayed as 0, but in reality has its sign bit set. Hence the -Inf result.

    Also note this explanation of the sign function (emphasis mine):

    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.

    Since -0 isn't less than zero, but instead equal to 0, sign returns 0.