Mathematics

Find mathematical algorithms in the math module, and the numbers available in the numbers module of the core library.

Numbers

Toit numbers support integers and floats.

Integers and floats

Integers are whole numbers such as -1, 0, 1, 2, 3, .. and they have type int. Floats are numbers with a decimal point. Floats are contagious, meaning that any binary operation involving a float forces the other operand to be converted to a float before doing the operation (thus yielding a float as result).

Integers are 64-bit signed integers. Floats are of size 64-bit, following the IEEE 754-1985 double format.

To make large numbers more readable, digits are often grouped using underscores. When storing these values and when displaying them on screen, Toit just ignores the underscores.

Underscores work for both integers and floats.

You can use the mathematics operators such as +, -, *, and / to form expressions that include numbers. The int class has additional operations (like bit-shifting) that are not supported by the floating point numbers.

Additional mathematical constants and functions are available in the math module.

import math

main:
  print (math.pow 2 10)

Randomization

random is a function included in the core library

random 10 gives you a random number between 0 and 10 (10 exclusive).

random 3 5 gives you a random number between 3 and 5 (5 exclusive).

Range

To create a range similar to the built-in function in Python:

range from/int to/int step=1 [block]:
  if step > 0:
    for i := from; i < to; i += step:
      block.call i
  else:
    for i := from; i > to; i += step:
      block.call i

main:
  range 5 10:
    print it  // Logs 5, 6, 7, 8, 9.
  range 10 20 2:
    print it  // Logs 10, 12, 14, 16, 18.

Bit operations

The bit operations on integers work on 64 bit signed twos-complement numbers. Thus the shift operators can take shift distances of up to 63:

  print 0x8000_0000_0000_0000 >>> 63  // >> 1

The shift-right operator, >> preserves the sign of its input, while the unsigned shift-right operator >>> shifts in zeros, which can give a positive result for a negative input.

  print -20 >> 2  // >> -5
  print -20 >>> 2 // >> 4611686018427387899

Shifting further than 63 will shift all bits out, rather than being undefined behavior (in C and C++) or taking the modulus of the shift distance (in Java):

  print -20 >> 64  // >> -1
  print -20 >>> 64 // >> 0

See the full documentation of operators on int and float.