Вопрос

EDU>> intmin 
    ans =

    -2147483648

EDU>> abs(intmin)

     ans =

     2147483647

How is this possible? There must be some sort of overflow or the definitions of these functions are mingling in strange ways.

Это было полезно?

Решение

For 2's complement signed integers of 32 bits, intmin is 0x80000000, or indeed -2147483648. However, intmax is 0x7FFFFFFF, which is only 2147483647. This means that the negation of intmin would be 2147483648, which can't be represented in 32-bit signed integers.

MATLAB actually does something odd. Under the normal rules of 2's complement, 0 - 0x80000000 should give 0x80000000 again. However, according to MATLAB, 0 - 0x80000000 = 0x7FFFFFFF. This should explain why abs(intmin) = intmax holds for MATLAB (but not necessarily in other languages).

This oddity has an interesting side-effect, however: you can assume that abs never returns a negative number.

Другие советы

In order to encode zero, there must be asymmetry among positive/negative two's complement integers.

Indeed, you are seeing integer overflow (saturation).

For each integer data type, there is a largest and smallest number that you can represent with that type:

integer_type_range

When the result of an expression involving integers exceeds the maximum (or minimum) value of the data type, MATLAB maps the values that are outside the limit to the nearest endpoint. This saturation behavior explains what you are seeing rather than a weird case of overflow in binary representation (which "wraps around" in 2's complement).

Example:

>> x = int8(100)
x =
  100
>> x + x
ans =
  127
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top