DEV Community

Andrey Frolov
Andrey Frolov

Posted on • Updated on

Elixir base arithmetic operations 🧪

Performing math operations and calculus is a very common thing to do with any programming language. Elixir offers several operators to help us work with numbers

Performing math operations and calculus is a very common thing to do with any programming language.

Elixir offers several operators to help us work with numbers.

  • Addition (+)
  • Subtraction (-)
  • Division (/)
  • Remainder (%)
  • Multiplication (*)
  • Exponentiation (**)

Addition (+)

 1 + 2
# => 3
Enter fullscreen mode Exit fullscreen mode

But the + operator doesn't serve as string concatenation if you use strings, so pay attention:

"asdas" + "asdas"
# => ** (ArithmeticError) bad argument in arithmetic # expression: 'asdas' + 'asdas'
#     :erlang.+('asdas', 'asdas')
Enter fullscreen mode Exit fullscreen mode

Subtraction (-)

Same as addition.

3-2
# => 1
Enter fullscreen mode Exit fullscreen mode

Division (/)

Returns the quotient of the first operator and the second:

Take a note, the result is a Float type, not an Integer. Operator / always return a Float, but if you want to do Integer division use div function.

20 / 5 
# => 4.0 (not a 4)

div(20,5)
# => 4
Enter fullscreen mode Exit fullscreen mode

If you try to divide by 0. You'll get an error.

1 / 0

# => ** (ArithmeticError) bad argument in arithmetic 
# expression: 1 / 0
#    :erlang./(1, 0)
Enter fullscreen mode Exit fullscreen mode

Remainder (rem)

The remainder is a very useful calculation in many use cases:

rem 20, 5
# => 0

rem 20, 7
# => 6

rem 1, 0
# => ** (ArithmeticError) bad argument in arithmetic #expression: rem(1, 0)
#    :erlang.rem(1, 0)
Enter fullscreen mode Exit fullscreen mode

Multiplication

Multiply two numbers

1 * 2 # => 2
-1 * 2 # => -2
Enter fullscreen mode Exit fullscreen mode

Exponentiation (**)

Raise the first operand to the power second operand. You can use math module

:math.pow(2, 3)
# => 8

:math.pow(3, 2)
# => 9
Enter fullscreen mode Exit fullscreen mode

One exception I found is that when raising a base number to an exponent, you probably don’t want to use the :math.pow/2 function.

:math.pow(42, 909)
# => ** (ArithmeticError) bad argument in arithmetic # expression
#    (stdlib) :math.pow(42, 909)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)