Julia Community 🟣

Vinod V
Vinod V

Posted on

Operators and Expressions in Julia

Operators and Expressions

Most statements (logical lines) that you write will contain expressions. A simple example of an expression is 2 + 3. An expression can be broken down into operators and operands.

Operators are functionality that do something and can be represented by symbols such as + or by special keywords. Operators require some data to operate on and such data is called operands. In this case, 2 and 3 are the operands.

Operators

We will briefly take a look at the operators and their usage.

Note that you can evaluate the expressions given in the examples using the interpreter interactively. For example, to test the expression 2 + 3, use the interactive Julia interpreter prompt:

julia> 2 + 3
5
julia> 3 * 5
15
julia>
Enter fullscreen mode Exit fullscreen mode

Here is a quick overview of the available operators:

  • + (plus)

    • Adds two objects
    • 3 + 5 gives 8.
  • - (minus)

    • Gives the subtraction of one number from the other; if the first operand is absent it is assumed to be zero.
    • -5.2 gives a negative number and 50 - 24 gives 26.
  • * (multiply)

    • Gives the multiplication of the two numbers or returns the string repeated that many times.
    • 2 * 3 gives 6. "ab" ^ 3 gives "ababab".
  • ^ (power)

    • Returns x to the power of y
    • 3 ^ 4 gives 81 (i.e. 3 * 3 * 3 * 3)
  • / (divide)

    • Divide x by y
    • 13 / 3 gives 4.333333333333333
  • div (divide and floor)

    • Divide x by y and round the answer down to the nearest integer value towards zero. Note that if one of the values is a float, you'll get back a float.
    • div(13,3) gives 4
    • div(-13,3) gives -4

    - div(9,1.81) gives 4.0

      #from julia documentation for div
      julia> div(4, 3, RoundDown) 
      1
      julia> div(4, 3, RoundUp) 
      2
      julia> div(5, 2, RoundNearest)
      2
      julia> div(5, 2, RoundNearestTiesAway)
      3
      julia> div(-5, 2, RoundNearest)
      -2
      julia> div(-5, 2, RoundNearestTiesAway)
      -3
      julia> div(-5, 2, RoundNearestTiesUp)
      -2
      julia> div(4, 3, RoundFromZero)
      2
      julia> div(-4, 3, RoundFromZero)
      -2
    
  • // (Divide two integers or rational numbers, giving a Rational result.)

    • (5//2) //(2//5) gives 25//4
  • % (modulo)

    • Returns the remainder of the division
    • 13 % 3 gives 1. -25.5 % 2.25 gives -0.75.
  • << (left shift)

    • Shifts the bits of the number to the left by the number of bits specified. (Each number is represented in memory by bits or binary digits i.e. 0 and 1)
    • 2 << 2 gives 8. 2 is represented by 10 in bits.
    • Left shifting by 2 bits gives 1000 which represents the decimal 8.
  • >> (right shift)

    • Shifts the bits of the number to the right by the number of bits specified.
    • 11 >> 1 gives 5.
    • 11 is represented in bits by 1011 which when right shifted by 1 bit gives 101which is the decimal 5.
  • & (bit-wise AND)

    • Bit-wise AND of the numbers: if both bits are 1, the result is 1. Otherwise, it's 0.
    • 5 & 3 gives 1 (0101 & 0011 gives 0001)
  • | (bit-wise OR)

    • Bitwise OR of the numbers: if both bits are 0, the result is 0. Otherwise, it's 1.
    • 5 | 3 gives 7 (0101 | 0011 gives 0111)
  • \xor<tab> (bit-wise XOR)

    • Bitwise XOR of the numbers: if both bits (1 or 0) are the same, the result is 0. Otherwise, it's 1.
    • 5 \xor<tab> 3 gives 6 (O101 xor 0011 gives 0110)
  • ~ (bit-wise invert)

    • The bit-wise inversion of x is -(x+1)
    • ~5 gives -6.
  • < (less than)

    • Returns whether x is less than y. All comparison operators return true or false. Note the small case of these names.
    • 5 < 3 gives false and 3 < 5 gives true.
    • Comparisons can be chained arbitrarily: 3 < 5 < 7 gives true.
  • > (greater than)

    • Returns whether x is greater than y
    • 5 > 3 returns true. Comparisons can be chained arbitrarily: 3 > 5 > 7 gives false.
  • <= (less than or equal to)

    • Returns whether x is less than or equal to y
    • x = 3; y = 6; x <= y returns true
  • >= (greater than or equal to)

    • Returns whether x is greater than or equal to y
    • x = 4; y = 3; x >= 3 returns true
  • == (equal to)

    • Compares if the objects are equal
    • x = 2; y = 2; x == y returns true
    • x = "str"; y = "stR"; x == y returns false
    • x = 'str'; y = 'str'; x == y returns true
  • != (not equal to)

    • Compares if the objects are not equal
    • x = 2; y = 3; x != y returns true
  • ! (boolean NOT)

    • If x is true, it returns false. If x is false, it returns true.
    • x = true; !x returns false.
  • && (boolean AND)

    • x && y returns false if x is false, else it returns evaluation of y
    • x = false; y = true; x && y returns false since x is false. In this case, Julia will not evaluate y since it knows that the left hand side of the 'and' expression is False which implies that the whole expression will be False irrespective of the other values. This is called short-circuit evaluation.
  • || (boolean OR)

    • If x is true, it returns True, else it returns evaluation of y
    • x = true; y = false; x || y returns true. Short-circuit evaluation applies here as well.

Shortcut for math operation and assignment

It is common to run a math operation on a variable and then assign the result of the operation back to the variable, hence there is a shortcut for such expressions:

a = 2
a = a * 3
Enter fullscreen mode Exit fullscreen mode

can be written as:

a = 2
a *= 3
Enter fullscreen mode Exit fullscreen mode

Notice that var = var operation expression becomes var operation= expression.

Evaluation Order

If you had an expression such as 2 + 3 * 4, is the addition done first or the multiplication? Our high school maths tells us that the multiplication should be done first. This means that the multiplication operator has higher precedence than the addition operator.

The following link gives the precedence table for Julia, from the lowest precedence (least binding) to the highest precedence (most binding). This means that in a given expression, Julia will first evaluate the operators and expressions lower in the table before the ones listed higher in the table.

Mathematical Operations and Elementary Functions Β· The Julia Language

Changing the Order Of Evaluation

To make the expressions more readable, we can use parentheses. For example, 2 + (3 * 4) is definitely easier to understand than 2 + 3 * 4 which requires knowledge of the operator precedences. As with everything else, the parentheses should be used reasonably (do not overdo it) and should not be redundant, as in (2 + (3 * 4)).

There is an additional advantage to using parentheses - it helps us to change the order of evaluation. For example, if you want addition to be evaluated before multiplication in an expression, then you can write something like (2 + 3) * 4.

Operator precedence of an operator > can be found out by the function Base.operator_precedence(:>)

julia> Base.operator_precedence(:^)
13
Enter fullscreen mode Exit fullscreen mode

Expressions

Example (save as expression.jl):

length = 5
breadth = 2

area = length * breadth
print("Area is ", area)
print("Perimeter is ", 2 * (length + breadth))
Enter fullscreen mode Exit fullscreen mode

Output:

$ julia expression.jl
Area is 10
Perimeter is 14
Enter fullscreen mode Exit fullscreen mode

How It Works

The length and breadth of the rectangle are stored in variables by the same name. We use these to calculate the area and perimeter of the rectangle with the help of expressions. We store the result of the expression length * breadth in the variable area and then print it using the print function. In the second case, we directly use the value of the expression 2 * (length + breadth) in the print function.

Summary

We have seen how to use operators, operands and expressions - these are the basic building blocks of any program. Next, we will see how to make use of these in our programs using statements.

Adapted from Operators and Expressions

Top comments (0)