Getting startedSlide 11 of 86
11/ 0Getting started

Arithmetic at the edges

None of these edge cases crashes; each one gives a value:

  • Dividing by zero, or taking a remainder by zero, gives 0, for an Int and a Float alike.
  • An Int wraps round. A sum, difference, product or power that would pass the largest Int, 9223372036854775807, comes back from the smallest, -9223372036854775808, and the other way round: a counter that passes the top turns negative. Negating the smallest Int gives itself, since it has no opposite.
  • ** on Ints is repeated multiplication, so 2 ** 100 wraps too, all the way round to 0. A negative exponent has no whole answer, so it gives 0, and n ** 0 is 1. For the real answer to a power, work in Float, where ** is true exponentiation.
  • A remainder takes the sign of the number divided, so -7 % 3 is -1, and % works on Floats.
  • Float arithmetic does reach infinity: 10.0 ** 400.0 is +Inf.

One case in the whole language is left unspecified: converting a Float that is infinite, not a number, or too large for an Int into one with hive.conv.ceil, floor or round. Check the range first if it matters.

proc main(): void {
	echo 1 / 0          // 0 — division by zero is a value, not a crash
	echo 1.0 / 0.0      // 0
	echo 5 % 0          // 0
	echo -7 % 3         // -1 — the remainder takes the sign of what is divided
	echo 7.5 % 2.0      // 1.5

	top := 9223372036854775807
	echo top + 1        // -9223372036854775808 — an Int wraps round
	echo -top - 10      // 9223372036854775799 — at either edge
	echo 2 ** 100       // 0
	echo 2 ** -1        // 0 — a negative Int exponent has no whole answer
	echo 10.0 ** 400.0  // +Inf — Float arithmetic does reach infinity
}