Truncation, Floor, Ceiling, and Rounding

Different ways of turning a fractional value into an integer behave differently at negative numbers and halfway cases.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
2 min
In this article4 chapters
  1. Think through a signed example
  2. Bill by started unit
  3. Start from an integer decision the program needs to make
  4. Specify signed values and ties

Think through a signed example

For minus 2.7, truncation toward zero yields minus two, floor yields minus three, and ceiling yields minus two. Python's int applied to that float truncates. Its floor division follows the floor rule for integer operands.

Bill by started unit

For 2.1 positive hours, billing by each started hour requires a ceiling of three hours. Billing completed hours requires a floor of two. A nearest-integer rule needs a documented tie convention. Python's round uses ties to even for exact halfway values of built-in numbers. Verify both sides of a rounding boundary.[1][2]

Start from an integer decision the program needs to make

A workspace schedules billing in complete half-hour blocks. An elapsed 61 minutes contains two completed blocks, with one minute left over. That is a floor computation on a nonnegative quotient. A policy charging for every started block instead counts three. This calls for a ceiling and depends on how exactly sixty minutes is handled. Write expected outcomes at 59, 60, and 61 minutes before converting to implementation operators. See half-open and inclusive boundaries.

Specify signed values and ties

If a time adjustment is minus 1.7 blocks, truncation toward zero yields minus one and floor gives minus two. Choose which is appropriate under a rule about signed adjustments. Some domains round halfway values away from zero. Python's built-in numeric rounding uses ties to even in exact halfway cases, so 2.5 and 3.5 can become two and four. A value entered as a decimal can land near such a tie when stored as binary floating point. In a test that checks a published rounding rule, use an exact decimal or exact binary tie according to the contract. Binary fraction rounding explains why the representable input matters.

References

  1. Python Software Foundation, Built-in Functions ↩
  2. Python Software Foundation, Python Standard Library: Built-in Types ↩