Operations#

Learning Objectives#

  • Perform basic arithmetic operations in Julia

  • Use logical operators to evaluate Boolean expressions

  • Apply comparison operators to compare values

  • Understand the syntax and usage of different operators in Julia

  • Implement basic mathematical and logical operations in Julia scripts

Arithmetic Operations#

Julia supports the standard arithmetic operators you are familiar with from other languages, including:

  • + (addition)

  • - (subtraction)

  • * (multiplication)

  • / (division) - Note: dividing two integers with / produces a Float64 result in Julia (e.g., 3/2 gives 1.5).

  • ÷ (integer division, also called floor division) - this gives the quotient of division rounded down to an integer. For example, 10 ÷ 3 results in 3 because 10/3 is 3.333.... As a tip, you can type the symbol ÷ by using a Julia REPL (or VS Code with the Julia extension) by typing - \div<tab>. You can also use the div(x, y) function to the same effect.

  • % (modulus) - the remainder of the division. For example, 10 % 3 results in 1.

  • ^ (exponentiation) - raising to a power. For example, 2 ^ 3 is 8.

The order of operations (precedence) in Julia follows standard math rules: for instance, multiplication/division happens before addition/subtraction unless you use parentheses to explicitly group. For example, 3 + 5 * 2 will yield 13 (since it calculated 5*2 first, then adds 3). If you want to force addition first, you will write (3 + 5) * 2, which would equal 16.

Some of the different operations and their results include:

x = 10
y = 3
println("x: ", x)
println("y: ", y)
println("Addition, x + y = ", x + y)        # 13
println("Subtraction, x - y = ", x - y)     # 7
println("Multiplication, x * y = ", x * y)  # 30
println("Division, x / y = ", x / y)        # 3.3333333333333335 (a Float64)
println("Floor Division, x ÷ y = ", x ÷ y)  # 3 (an Int)
println("Modulus, x % y = ", x % y)         # 1
println("Exponentiation, x ^ y = ", x ^ y)  # 1000 (10^3)
x: 10
y: 3
Addition, x + y = 13
Subtraction, x - y = 7
Multiplication, x * y = 30
Division, x / y = 3.3333333333333335
Floor Division, x ÷ y = 3
Modulus, x % y = 1
Exponentiation, x ^ y = 1000

Exercise: Calculating the Average of Two Numbers#

Given two numbers, write a short code snippet that computes their average and print it. For instance, for a = 7and b = 4, the average is (7+4)/2 = 5.5, test your code with different pairs of numbers (including a pair of integers and a pair of floats).

# Answer here

Comparison Operations#

Comparison operators in Julia are used to compare values and yield Boolean results (true or false). These include:

  • == (equality test) - e.g. 5 == 5 yields true, 5 == 3 yields false. Remember to use == for comparison, not a single =, which is an assignment.

  • != (inequality test) - e.g. 5 != 3 yields true, 5 != 5 yields false `!= can be read as “not equal to”.

  • < (less than), > (greater than) - e.g. 7 < 10 is true, 7 < 10 is false.

  • <= (less than or equal to), >= (greater than or equal to) - e.g. 3 <= 3 is true (since it’s equal), 4 >= 5 is false.

  • === (Identity) - Test for object identity and exact bitwise equality. Useful for when you need to distinguish, for example, an integer from a floating-point value.

  • isa (Type-Test Operator) - Checks whether a value belongs to a given type (including subtypes).

You can chain comparisons in Julia, which can make certain checks elegant. For example, to check if x is between 0 and 100, you can do: 0 <= x <= 100. This will produce true if and only if x is between 0 and 100 (inclusive). Julia evaluates chained comparisons in the mathematically expected way, similar to Python.

x = 5
y = 10

println("Is x equal to y?        ", x == y)        # false, 5 is not equal to 10
println("Is x not equal to y?    ", x != y)        # true, 5 is not equal to 10
println("Is x less than y?       ", x < y)         # true, 5 < 10
println("Is x greater than y?    ", x > y)         # false, 5 > 10 is false
println("Is x ≤ y?               ", x <= y)        # true, 5 is less than or equal to 10
println("Is x ≥ y?               ", x >= y)        # false, 5 is not ≥ 10

println("Is x between 0 and y?   ", 0 <= x <= y)   # true iff 0 ≤ 5 ≤ 10

a = 2        # Int
b = 2.0      # Float64

println("Is a identical to b?    ", a === b)        # false, 2 (Int) vs 2.0 (Float64)
println("Is a equal to b?        ", a == b)

println("Is x an Int?            ", x isa Int)    # true
println("Is y a Float64?         ", y isa Float64)   # false
Is x equal to y?        false
Is x not equal to y?    true
Is x less than y?       true
Is x greater than y?    false
Is x ≤ y?               true
Is x ≥ y?               false
Is x between 0 and y?   true
Is a identical to b?    false
Is a equal to b?        true
Is x an Int?            true
Is y a Float64?         false

Exercise: Comparison Operations#

Using the variables a = 15 and b = 20, write an expression to check the following and print the results:

  • whether a is at least 10,

  • whether a and b are equal

  • whether a is between 10 and 20 inclusive.

# Answer here

Logical (Boolean) Operations#

Logical operators let you combine or invert Boolean values. They all return true or false.

  • AND: (&&) – returns true if both operands are true. Short-circuits if the first operand is false (the second isn’t evaluated).

  • OR: (||) – returns true if at least one operand is true. Short-circuits if the first operand is true (the second isn’t evaluated).

  • NOT: (!) – unary operator that negates a Boolean value.

  • Bitwise & Elementwise: (& and |) – do not short-circuit. Use for bitwise AND/OR on integers or element-wise operations on arrays.

a = true
b = false

println("a:             ", a)          # true
println("b:             ", b)          # false
println("a AND b:       ", a && b)     # false (b is false)
println("a OR b:        ", a || b)     # true  (a is true)
println("NOT a:         ", !a)         # false (negates true)
a:             true
b:             false
a AND b:       false
a OR b:        true
NOT a:         false

Of course, we can use actual comparisons in place of a and b to form compound logical expressions. For instance:

x = 7

# print whether x is positive AND x is odd
println((x > 0) && (x % 2 == 1))
true

We can also chain multiple Boolean operations together:

# Check whether each vowel is in the word or 'y' is *not* in the word
# word = Consequentially
word = "Consequentially"
condition = ('a' in word) && ('e' in word) && ('i' in word) && ('o' in word) && ('u' in word) || !('y' in word)
println("$(word): ", condition)

# word = Counterfactual
word = "Counterfactual"
condition = ('a' in word) && ('e' in word) && ('i' in word) && ('o' in word) && ('u' in word) || !('y' in word)
println("$(word): ", condition)
Consequentially: true
Counterfactual: true

A trick with ||#

When evaluating a || b, it’s actually more precise to say that || returns true if a is true or else it evaluates to the value of b. For example:

# Evaluates to the value of the second argument
(1 == 2) || "fish"
"fish"

This may seem a bit odd, but it does have some useful applications. For example, we can use it in the following ‘guard’ pattern to throw an error is some condition isn’t met:

# Throw error if number negative
x = -3
(x >= 0) || error("x cannot be negative")
x cannot be negative

Stacktrace:
 [1] error(s::String)
   @ Base .\error.jl:35
 [2] top-level scope
   @ In[9]:3

Exercise: Writing Conditions#

Consider two variables, score = 85 and max_score = 100. Write a condition that can be used to check whether the score is within a valid range (say 0 to max_score inclusive) and that the percentage score (score/max_score) is at least 80%. For bonus points, get it to print the text “Didn’t pass” if one of these conditions isn’t satisfied.

# Answer here

Extension exercise: what about &&?#

We discussed how || evaluates to the final argument if the first argument is true. What do you think the analogous statement is for &&?

End of Section Quiz#

Which operator would you use in Julia for exponentiation (raising to a power)?

What is the result of the expression `10 < 5 || 2 + 2 == 4` in Julia?