Skip to content

Arithmetic

Arithmetic is about the stuff you learn to do with numbers in primary school: Addition, Subtraction, Multiplication, Division and so on. Piece of cake. We all know that stuff. We nonetheless want to spend a whole section on this topic, because when it comes to computers the devil is in the details.

As introduced in Primitives numeric types in Pony are represented as a special kind of primitive that maps to machine words. Both integer types and floating point types support a rich set of arithmetic and bit-level operations. These are expressed as Infix Operators that are implemented as plain functions on the numeric primitive types.

What should happen when you add one to the largest number an integer type can hold? Pony gives you a choice of operators depending on whether you want the result to wrap around, want to detect overflow, or already know the result will fit.

Numeric Fundamentals

Already familiar with integer widths, signed vs. unsigned, and overflow? Skip ahead.

Integer Widths

The number in a type name like U8 or I32 is the number of bits used to store the value. More bits means a wider range of representable values:

Type Bits Minimum Maximum
U8 8 0 255
I8 8 -128 127
U32 32 0 4294967295
I32 32 -2147483648 2147483647

The pattern: an N-bit unsigned type can hold values from 0 to 2N - 1. An N-bit signed type splits its range roughly in half, covering -2N-1 to 2N-1 - 1.

Signed vs. Unsigned

Unsigned integer types (U8, U16, U32, etc.) represent only non-negative values. All N bits contribute to the magnitude, so the maximum value for a U8 is 255 (28 - 1).

Signed integer types (I8, I16, I32, etc.) use two’s complement representation, which gives them an asymmetric range. For example, I8 covers -128 to 127, not -127 to 127. There is one more negative value than positive because zero takes up one of the non-negative slots.

Overflow and Underflow

When an arithmetic operation produces a result outside the representable range, it overflows (too large) or underflows (too small). With fixed-width integers, wrap-around can occur:

// Unsigned wrap-around: the value wraps from the maximum back to zero
U8(255) + 1 == 0

// Unsigned wrap-around: the value wraps from zero to the maximum
U8(0) - 1 == 255

// Unsigned integer literal wrap-around: negative literals get wrapped as well
U8(-1) == 255

// Signed integers: zero is in the middle of the range, not at the edge
// Compare with U8(0) - 1 above — for signed integers, this is just normal subtraction
I8(0) - 1 == -1

// Signed wrap-around: going past the maximum wraps to the minimum
I8(127) + 1 == -128

// Signed wrap-around: going past the minimum wraps to the maximum
I8(-128) - 1 == 127

A U8 has eight bits. Adding one to 255 gives 256, which takes nine bits to write in binary. With ordinary addition, Pony keeps the low eight bits, which are all zero. For an N-bit integer, keeping the low N bits is arithmetic modulo 2N.

Integers

Pony’s default Integer Arithmetic

Integer addition, subtraction, multiplication and negation wrap around when the result falls outside the type’s range. For signed integers, the same bits are interpreted using two’s complement.

// unsigned wrap-around on overflow
U32.max_value() + 1 == 0

// signed wrap-around on overflow/underflow
I32.min_value() - 1 == I32.max_value()

Division by zero is a special case, which affects the division / and remainder % operators. In Mathematics, division by zero is undefined. In order to avoid either defining division as partial, throwing an error on division by zero or introducing undefined behaviour for that case, the normal division is defined to be 0 when the divisor is 0. This might lead to silent errors, when used without care. Choose Partial and checked Arithmetic to detect division by zero.

Wrapping gives you a defined result without checking whether overflow occurred.


Operator Method Description
+ add() wrap around on over-/underflow
- sub() wrap around on over-/underflow
* mul() wrap around on over-/underflow
/ div() x / 0 = 0
% rem() x % 0 = 0
%% mod() x %% 0 = 0
- neg() wrap around on over-/underflow
>> shr() fills with the sign bit for signed integers, zeros for unsigned integers
<< shl() fills the low bits with zeros

Unsafe Integer Arithmetic

Unsafe addition assumes the result fits in the integer type. For example, U8(255) +~ 1 overflows, so its behaviour is undefined. The compiler can optimise on the assumption that overflow never occurs. Use ordinary + if you need the result to wrap around.

The table lists unsafe integer operators. For both shifts, the shift count must be less than the integer width.


Operator Method Undefined in case of
+~ add_unsafe() Overflow E.g. I32.max_value() +~ I32(1)
-~ sub_unsafe() Overflow
*~ mul_unsafe() Overflow.
/~ div_unsafe() Division by zero and overflow. E.g. I32.min_value() /~ I32(-1)
%~ rem_unsafe() Division by zero and overflow.
%%~ mod_unsafe() Division by zero and overflow.
-~ neg_unsafe() Overflow. E.g. -~I32.min_value()
>>~ shr_unsafe() If non-zero bits are shifted out. E.g. I32(1) >>~ U32(2)
<<~ shl_unsafe() Signed: bits differing from the final sign bit are shifted out. Unsigned: nonzero bits are shifted out.

Unsafe Conversion

Converting between integer types in Pony needs to happen explicitly. Each numeric type can be converted explicitly into every other type.

// converting an I32 to a 32 bit floating point
I32(12).f32()

Each conversion has an unsafe counterpart. For example, u8_unsafe() converts an integer to a U8 provided its value fits in the range 0 to 255. An I64 takes up more space than a U8, but I64(1).u8_unsafe() still returns 1. If you call the same method on I64(256) or I64(-1), the result is undefined. You can find the conditions for each unsafe conversion in the standard library reference.

I64(1).u8_unsafe()
I64(255).u8_unsafe()

What if you convert an integer to a floating-point type? In this example the integer 12 is exactly representable as an F32, so the result is 12.0.

I32(12).f32_unsafe()

Here is a full list of all available conversions for numeric types:


Safe conversion Unsafe conversion
u8() u8_unsafe()
u16() u16_unsafe()
u32() u32_unsafe()
u64() u64_unsafe()
u128() u128_unsafe()
ulong() ulong_unsafe()
usize() usize_unsafe()
i8() i8_unsafe()
i16() i16_unsafe()
i32() i32_unsafe()
i64() i64_unsafe()
i128() i128_unsafe()
ilong() ilong_unsafe()
isize() isize_unsafe()
f32() f32_unsafe()
f64() f64_unsafe()

Partial and Checked Arithmetic

If your program needs to detect overflow, use partial or checked arithmetic. For example, U8(255) +? 1 raises an error that you can handle in a try expression. The checked method U8(255).addc(1) returns (0, true). The first element is the wrapped sum and the second tells you that it overflowed.

// partial arithmetic
let result =
  try
    USize.max_value() +? env.args.size()
  else
    env.out.print("overflow detected")
  end

// checked arithmetic
let result =
  match USize.max_value().addc(env.args.size())
  | (let result: USize, false) =>
    // use result
...
| (_, true) =>
  env.out.print("overflow detected")
end
Partial Operator Method Description
+? add_partial() errors on overflow/underflow
-? sub_partial() errors on overflow/underflow
*? mul_partial() errors on overflow/underflow
/? div_partial() errors on overflow/underflow and division by zero
%? rem_partial() errors on overflow/underflow and division by zero
%%? mod_partial() errors on overflow/underflow and division by zero

Checked arithmetic functions all return the result of the operation and a Boolean flag indicating overflow/underflow or division by zero in a tuple.

Checked Method Description
addc() Checked addition, second tuple element is true on overflow/underflow.
subc() Checked subtraction, second tuple element is true on overflow/underflow.
mulc() Checked multiplication, second tuple element is true on overflow.
divc() Checked division, second tuple element is true on overflow or division by zero.
remc() Checked remainder, second tuple element is true on overflow or division by zero.
modc() Checked modulo, second tuple element is true on overflow or division by zero.
fldc() Checked floored division, second tuple element is true on overflow or division by zero.

Floating Point

Pony default arithmetic on floating point numbers (F32, F64) behave as defined in the floating point standard IEEE 754.

That means e.g. that division by +0 returns Inf and by -0 returns -Inf.

Unsafe Floating Point Arithmetic

Unsafe Floating Point operations do not necessarily comply with IEEE 754 for every input or every result. If any argument to an unsafe operation or its result are +/-Inf or NaN, the result is actually undefined.

This allows more aggressive optimizations and for faster execution, but only yields valid results for values different that the exceptional values +/-Inf and NaN. We suggest to only use unsafe arithmetic on floats if you can exclude those cases.


Operator Method
+~ add_unsafe()
-~ sub_unsafe()
*~ mul_unsafe()
/~ div_unsafe()
%~ rem_unsafe()
%%~ mod_unsafe()
-~ neg_unsafe()
<~ lt_unsafe()
>~ gt_unsafe()
<=~ le_unsafe()
>=~ ge_unsafe()
=~ eq_unsafe()
!=~ ne_unsafe()

Additionally sqrt_unsafe() is undefined for negative values.