Captain / Documentation / Part 5. Numbers

Division and rounding

Contents ↓

Captain makes one promise about decimals: every point where a decimal loses digits is written in the program. Addition, subtraction and multiplication never lose any (Exact decimals). Division can, because most quotients have no end: one divided by three is 0.333... for ever. This chapter explains what / does about that, the two operations that drop digits on purpose, the seven rounding modes, and the patterns that everyday calculations need: splitting a bill, percentages, averages and tax.

The rules are decided in DR-0034.

/ is exact or fails

a / b on two decimals gives the quotient exactly. When no decimal can hold the quotient exactly, the run stops with CAP-RUN-INEXACT, and the message says what to write instead.

division.capt
module Example::Division.

export quotient a: Decimal b: Decimal -> Decimal [
  ret a / b.
].

export cents x: Decimal mode: Symbol -> Decimal [
  ret x scale: 2 rounding: mode.
].

export share a: Decimal b: Decimal places: i32 -> Decimal [
  ret a divide: b scale: places rounding: #HalfEven.
].

;; One mode applied to 2.5, -2.5 and 2.6, each rounded to a whole number.
export modes mode: Symbol -> List[Decimal] [
  ret #( (2.5 scale: 0 rounding: mode),
         ((0.0 - 2.5) scale: 0 rounding: mode),
         (2.6 scale: 0 rounding: mode) ).
].
Terminal
$ captain build division.capt -o division.capb
built division.capb ([..] bytes, sha256 [..])
$ captain run division.capb quotient a=10.01 b=2.00
run log: quotient.runlog
5.005
$ captain run division.capb quotient a=10.00 b=4.0
run log: quotient.runlog
2.50
$ captain run division.capb quotient a=1.0 b=4.0
run log: quotient.runlog
0.25
$ captain run division.capb quotient a=3.0 b=1.5
run log: quotient.runlog
2.0
$ captain run division.capb quotient a=7 b=2
run log: quotient.runlog
3.5
$ captain run division.capb quotient a=100 b=0.25
run log: quotient.runlog
400.00
$ captain run division.capb quotient a=1.0 b=3.0
run log: quotient.runlog
error[CAP-RUN-INEXACT]: 1.0 / 3.0 has no exact decimal quotient: `/` never drops digits. Say where the quotient is cut and how: `a divide: b scale: 2 rounding: #HalfEven`
$ captain run division.capb quotient a=5 b=0
run log: quotient.runlog
error[CAP-RUN-ARITH]: arithmetic failure (overflow or /0)

Division by zero is CAP-RUN-ARITH, as it is for integers.

Which quotients are exact

A quotient has an exact decimal when the divisor, once the fraction is reduced, has no prime factors other than 2 and 5, the factors of ten. Dividing by 2, 4, 5, 8, 10, 20, 25 or 100 is always exact. Dividing by 3, 6, 7 or 12 is exact only when the numerator cancels the awkward factor, as in 4.5 / 3.0, which is 1.5, or 1200.00 / 12.0, which is 100.00. Whether a division is exact usually depends on the values, so a program that divides by something that comes from data should say how to round, unless it knows the division is exact.

The scale of a quotient

The quotient takes the smallest scale that holds it exactly and is at least the larger of the two operands' scales:

  • 10.00 / 4.0 is 2.50: the quotient 2.5 needs one place, but the larger operand scale is 2, so it has two.
  • 10.01 / 2.00 is 5.005: the operands have two places, but the quotient needs three, so it has three.
  • 100 / 0.25 is 400.00: the scale never drops below the operands'.

Why not a fixed scale, say the larger operand scale, and fail when the quotient does not fit it? Then 1.0 / 4.0 would fail, though nothing is lost, and every average over two or four values, and every share of a hundred, would need a rounding that rounds nothing. Captain gives exact quotients and refuses inexact ones.

Why not truncate, as many languages do, and offer rounding for those who want better? Then a program that forgot to round would still run, and still give an answer, and the answer would be silently wrong. That is the mistake a reviewer is least likely to catch: total / count looks right. With / exact or failing, the forgotten rounding shows up the first time the division is inexact, as a stopped run that names the operands.

Rounding names its scale and its mode

Two operations drop digits, and nothing else does:

Written Gives
x scale: n rounding: #Mode x at exactly n decimal places
a divide: b scale: n rounding: #Mode a / b at exactly n decimal places

n is an i32. Raising the scale only adds zeros; lowering it drops digits, by the mode. divide:scale:rounding: works out the quotient to the scale asked for and rounds once, so `1.0 divide: 3.0 scale: 4 rounding:

HalfUpis0.3333, where1.0 / 3.0` would have stopped the run.

Terminal
$ captain run division.capb cents x=12.345 mode=HalfEven
run log: cents.runlog
12.34
$ captain run division.capb cents x=12.345 mode=HalfUp
run log: cents.runlog
12.35
$ captain run division.capb cents x=12.5 mode=Down
run log: cents.runlog
12.50
$ captain run division.capb share a=1 b=3 places=4
run log: share.runlog
0.3333
$ captain run division.capb share a=2 b=3 places=2
run log: share.runlog
0.67
$ captain run division.capb share a=10 b=4 places=0
run log: share.runlog
2

The result always has exactly the scale asked for, so Text from: shows exactly that many places: rounding to scale 2 is also how a program formats an amount with two places.

The spelling says where and how. Smalltalk's roundTo: 0.01, (x rounded), (x truncated) and (x floor), setScale: from Java, and divide:scale: without a mode each leave one of the two out. The checker refuses them with a help line that names Captain's form: (x scale: 2 rounding: #HalfEven).

The seven modes

A mode is a symbol:

Mode Drops digits 2.5 -2.5 2.6
#HalfEven to the nearest; a tie to the even neighbour 2 -2 3
#HalfUp to the nearest; a tie away from zero 3 -3 3
#HalfDown to the nearest; a tie toward zero 2 -2 3
#Down toward zero 2 -2 2
#Up away from zero 3 -3 3
#Floor toward negative infinity 2 -3 2
#Ceiling toward positive infinity 3 -2 3

Each row of the table is the modes entry above, run with that mode:

Terminal
$ captain run division.capb modes mode=HalfEven
run log: modes.runlog
#( 2, -2, 3 )
$ captain run division.capb modes mode=HalfUp
run log: modes.runlog
#( 3, -3, 3 )
$ captain run division.capb modes mode=HalfDown
run log: modes.runlog
#( 2, -2, 3 )
$ captain run division.capb modes mode=Down
run log: modes.runlog
#( 2, -2, 2 )
$ captain run division.capb modes mode=Up
run log: modes.runlog
#( 3, -3, 3 )
$ captain run division.capb modes mode=Floor
run log: modes.runlog
#( 2, -3, 2 )
$ captain run division.capb modes mode=Ceiling
run log: modes.runlog
#( 3, -2, 3 )

The three "half" modes differ only on an exact tie. #HalfEven, often called banker's rounding, sends ties up and down equally often, so a long column of rounded figures does not drift; #HalfUp is the rule taught in school. #Down is plain truncation. #Floor and #Ceiling are for limits: the number of whole disks needed to hold some data is a #Ceiling, the number of whole items a budget buys is a #Floor. Which mode a calculation needs is a business rule, often written down in a contract or a regulation; Captain does not choose one for you, and the program says which it follows.

Modes are checked before the run

A mode written as a literal is checked when the program is checked. An unknown one is CAP-TYPE-032, and the help line names the mode it was probably meant to be. Common names from other languages are recognised: #Bankers and #halfEven are #HalfEven, #Truncate is #Down, #Ceil is #Ceiling.

Refused by the checker: CAP-TYPE-032
module Example::Bankers.

export cents x: Decimal -> Decimal [
  ret x scale: 2 rounding: #Bankers.
].
Terminal
$ captain check bankers.capt
error[CAP-TYPE-032]: `#Bankers` is not a rounding mode
  --> bankers.capt:4:28
4 |   ret x scale: 2 rounding: #Bankers.
  |                            ^^^^^^^^
  help: did you mean `#HalfEven`?
checked 1 file as 1 module, 1 with errors

A mode or a scale that is computed, or passed in as an argument as in cents x:mode: and share a:b:places: above, can only be checked when the program runs. A symbol that is not a mode, or a negative scale, stops the run with CAP-RUN-RANGE, as an index out of range does:

Terminal
$ captain run division.capb cents x=12.345 mode=Bankers
run log: cents.runlog
error[CAP-RUN-RANGE]: #Bankers is not a rounding mode; the modes are #HalfEven, #HalfUp, #HalfDown, #Down, #Up, #Floor and #Ceiling
$ captain run division.capb share a=2 b=3 places=-1
run log: share.runlog
error[CAP-RUN-RANGE]: scale -1 is negative; a scale counts decimal places

A large scale is not a problem. Every step is checked for overflow, and nothing loops in proportion to the scale, so a scale supplied by a host costs what any other does.

Integer division still truncates

None of this changes integers. / on two i32 or two i64 values truncates toward zero, so -7 / 2 is -3, as Integers, booleans and conversion shows. Integers are for counting, and a count divided by a count is usually meant to be a whole number. When it is not, make the integers decimals with as: and divide those.

Splitting a bill so the parts add up

Three people sharing 100.00 cannot each pay a rounded third: 33.33 three times is 99.99, and a cent is lost. Rounding each share does not fix it, whichever mode is chosen. The remainder has to be handed out explicitly:

bill.capt
module Example::Bill.

;; Split a total in cents into equal parts that add up to the total.
;; Rounding toward negative infinity leaves a remainder that is never
;; negative; it is handed out one cent at a time to the first parts.
export split total: Decimal parts: i32 -> List[Decimal] [
  n := parts as: Decimal.
  each := total divide: n scale: 2 rounding: #Floor.
  left := total - (each * n).
  out := List empty: Decimal.
  i := 0.
  [ i < parts ] whileTrue: [
    part := each.
    (left > 0.00) ifTrue: [
      part := each + 0.01.
      left := left - 0.01.
    ].
    out := out push: part.
    i := i + 1.
  ].
  ret out.
].

;; The parts added up again, as a check.
export total total: Decimal parts: i32 -> Decimal [
  sum := 0.00.
  (split total: total parts: parts) forEach: [ :p | sum := sum + p ].
  ret sum.
].
Terminal
$ captain build bill.capt -o bill.capb
built bill.capb ([..] bytes, sha256 [..])
$ captain run bill.capb split total=100.00 parts=3
run log: split.runlog
#( 33.34, 33.33, 33.33 )
$ captain run bill.capb split total=-100.00 parts=3
run log: split.runlog
#( -33.33, -33.33, -33.34 )
$ captain run bill.capb split total=0.05 parts=3
run log: split.runlog
#( 0.02, 0.02, 0.01 )
$ captain run bill.capb split total=10.00 parts=4
run log: split.runlog
#( 2.50, 2.50, 2.50, 2.50 )
$ captain run bill.capb total total=100.00 parts=7
run log: total.runlog
100.00

#Floor is chosen on purpose: it rounds every share down, toward negative infinity, so what is left over is always zero or more, for a refund as well as a charge. Who gets the extra cents, here the first parts, is a rule the program states where a reader can see it.

Percentages

A percentage is a ratio times a hundred. Multiply first and divide last, so only one step can be inexact, and round that step:

percent.capt
module Example::Percent.

;; How much of a budget is spent, in percent, to one decimal place.
export used spent: Decimal budget: Decimal -> Decimal [
  ret (spent * 100.0) divide: budget scale: 1 rounding: #HalfUp.
].

;; A price raised by a percentage, to the cent.
export raise price: Decimal percent: Decimal -> Decimal [
  raised := price + ((price * percent) / 100.0).
  ret raised scale: 2 rounding: #HalfUp.
].
Terminal
$ captain build percent.capt -o percent.capb
built percent.capb ([..] bytes, sha256 [..])
$ captain run percent.capb used spent=4120.00 budget=12000.00
run log: used.runlog
34.3
$ captain run percent.capb used spent=1 budget=3
run log: used.runlog
33.3
$ captain run percent.capb raise price=19.99 percent=3.5
run log: raise.runlog
20.69

In raise price:percent:, / 100.0 needs no rounding: dividing by a hundred is always exact. The price is rounded once, at the end, to the cent.

Averages

The mean of some values is their sum divided by their count. The count is an integer, so it becomes a decimal with as:, and the division names its scale, because a sum divided by three is rarely exact:

average.capt
module Example::Average.

;; The mean of some figures, to two places.
average values: List[Decimal] -> Decimal [
  sum := 0.0.
  values forEach: [ :v | sum := sum + v ].
  ret sum divide: ((values count) as: Decimal) scale: 2 rounding: #HalfEven.
].

;; The mean of three monthly figures.
export quarter jan: Decimal feb: Decimal mar: Decimal -> Decimal [
  ret average values: #( jan, feb, mar ).
].
Terminal
$ captain build average.capt -o average.capb
built average.capb ([..] bytes, sha256 [..])
$ captain run average.capb quarter jan=1250.00 feb=980.50 mar=1104.25
run log: quarter.runlog
1111.58
$ captain run average.capb quarter jan=10 feb=20 mar=30
run log: quarter.runlog
20.00

An empty list makes the count zero, and the division stops the run with CAP-RUN-ARITH. A program that may see no figures tests (values isEmpty) first and decides what the average of nothing is.

Tax at a stated scale

Tax rules say where the rounding happens: on each line of an invoice, or once on the total. The two can differ by a cent or more, and a program has to follow the rule it is given. Both are easy to write, and the source says which one it is:

tax.capt
module Example::Tax.

;; Tax on an invoice of identical lines, rounded on each line...
export taxPerLine price: Decimal lines: i32 rate: Decimal -> Decimal [
  each := (price * rate) scale: 2 rounding: #HalfUp.
  ret each * (lines as: Decimal).
].

;; ...or once, on the total.
export taxOnTotal price: Decimal lines: i32 rate: Decimal -> Decimal [
  ret ((price * (lines as: Decimal)) * rate) scale: 2 rounding: #HalfUp.
].
Terminal
$ captain build tax.capt -o tax.capb
built tax.capb ([..] bytes, sha256 [..])
$ captain run tax.capb taxPerLine price=0.99 lines=3 rate=0.20
run log: taxPerLine.runlog
0.60
$ captain run tax.capb taxOnTotal price=0.99 lines=3 rate=0.20
run log: taxOnTotal.runlog
0.59

Each line's tax is 0.198, which rounds to 0.20, so three lines are 0.60. The total is 2.97, whose tax is 0.594, which rounds to 0.59. Neither answer is wrong; they follow different rules. An auditor reading the program can see which rule it follows, at which scale and in which mode.

Programs built before exact division

Exact division, the rounding operations and n as: Decimal arrived with VM generation 7, in the 0.7.0 release; see Versions and VM generations. Before that, / on decimals truncated toward zero at the larger operand scale, without saying so: 10.01 / 2.00 was 5.00, and 1.0 / 3.0 was 0.3.

An artifact built before then keeps that meaning. Its / was compiled to an instruction that truncates, and that instruction still truncates, in every generation, so the artifact and its run records go on running and replaying exactly as they did. A generation's meaning never changes once it is released (DR-0017). What changes is the compiler: the same source, built today, compiles / to exact division, needs generation 7, and fails where the old artifact truncated. Rebuilding a program that divides decimals is therefore a change to review, not a formality.