Mathematics in Toit
Find mathematical algorithms in the math module, and the numbers available in the numbers module of the core library.
Toit numbers support integers and floats.
Integers and floats
Integers are whole numbers such
as -1, 0, 1, 2, 3, .. and they have type
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
/ to form expressions that include numbers.
The int class has additional
operations (like bit-shifting) that are not supported by the floating point
Additional mathematical constants and functions are available in the math module.
random is a function included in the
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).
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.
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:
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.
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):