Sign and Absolute Value in Integer Calculations

Absolute value measures distance from zero. Keeping the original sign can be essential for position, direction, or accounting.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Choose a signed representation
  2. Prove a boundary case
  3. Interpret signs before comparing magnitudes
  4. Check representable endpoints

Choose a signed representation

If a sensor reports offsets of minus two and plus four from a reference, the sum is two. Summing the distances gives six. These answer different questions. Use names carrying meaning such as signed_offset and distance to show which rule applies.

Prove a boundary case

In a signed eight-bit representation ranging from minus 128 to 127, 128 is beyond the positive range. An absolute-value operation on the minimum needs a wider type or a documented overflow outcome. Integer widening matters any time a count crosses between representations.[1][2]

Interpret signs before comparing magnitudes

A shop counts a return of four items as minus four, and a sale of seven as plus seven in one movement report. Their net is three. Taking absolute values before adding gives eleven units of total movement. Adding first and taking the absolute value gives three units of net movement magnitude. Those are all well-defined computations, and only the inclusion of signs tells which activity changed the stock. See naming values with meaning for separating these counters in code.

Check representable endpoints

On a signed eight-bit two's-complement interface, an input of minus 128 has mathematical magnitude 128. That result does not fit in the signed eight-bit positive range. Widening the working representation before computing magnitude can preserve it. Storing the result back in the narrow field still needs a supported conversion. Two's-complement reading gives the asymmetric endpoints. Test minus one, zero, the smallest supported signed value, and an ordinary positive value. Include results wanted by the next stage as part of the contract. A magnitude used in a distance is nonnegative and may have a different allowable range from the original signed quantity.

References

  1. Python Software Foundation, Python Standard Library: Built-in Types ↩
  2. Python Software Foundation, Python Language Reference: Expressions ↩