Course of Raku / Essentials / Numbers

Operations with numbers

There is no doubt you already know some of the operations you can do with Raku numbers. Just to mention that the symbol of the operation is called an operator. The objects on which we perform operations are called operands.

Arithmetics

Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division

As Raku supports Unicode really well, some of these operators have non-ASCII equivalents:

× Multiplication
÷ Division

To change the order of execution, use parentheses:

say 3 * 4 + 5;   # 17
say 3 * (4 + 5); # 27

Modulo

The modulo operator is % as in many other languages.

% Modulo

It returns the remainder of the integer division of two numbers, so 10 % 3 is 1. Note that -10 % 3 is 2 as the result of the operation is defined as the difference between the first number and the rounded-down division multiplied by the second number. So, $a % $b is equivalent to $a - $b * floor($a / $b).

Divisibility

Raku adds a useful operator to test if the number is divisible by another number.

%% Divisibility

This is an infix operator that needs two operands: 10 %% 3. If the first operand is divisible by the second operand, the result is a Boolean True. Otherwise, False.

Integer operations

There are special operations that return integer results. Their operators are words instead of symbols.

div Integer division
mod Integer modulo

The div operator rounds down the result, so 10 div 3 is 3, and -10 div 3 is -4.

Both div and mod expect integer operands. So, the following program will not work if you uncomment the lines marked as Error:

say 10.3 % 3;     # OK
# say 10.3 mod 3; # Error

say 10.3 / 3.3;     # OK
# say 10.3 div 3.3; # Error

Power

There are two ways of getting the result of x to the power of y. First, you can use the ** operator:

say 3 ** 4; # 81

Second, you can use superscript digits, for example:

say 3; # 81

It is possible to put more than one superscript digit to get the value of power bigger than 9. For example:

say 2¹⁵; # 32768

Negative power is not a problem either:

say 2 ** (-2); ## 0.25
say 2²; # 0.25

Notice that the result of the last two expressions is a Rat number.

Operations with assignment

All the operations support the shortcut syntax when you need to update the variable. Let us demonstrate it on the example of +.

The full form

$a = $a + $b;

is equivalent to:

$a += $b;

Course navigation

Numbers / Floating-point numbers   |   💪 Exercises: Numbers

Translations of this page: EnglishDeutschEspañolItalianoLatviešuNederlandsБългарскиРусскийУкраїнська