DEV Community

Cover image for Learning Julia (2): Operations
Z. QIU
Z. QIU

Posted on • Edited on

1

Learning Julia (2): Operations

Get familiar with Operators in Julia.

Mathematical operations


# Math Operators + - * / \ ^ % div()
a = 2 + 3 #  5
b = 4 - 1 #  3
c = 5 * 4 # 20
d = 32 / 4 # 8.0
e = 15 / 2 # 7.5 #  Int divided by Int gives Float
f= div(15, 2) # 7 # floor rounded 
g = div(-15, 2) # -7
h = 5 \ 35 # 7.0
i = 12 % 10 # 2
j = 2 ^ 3 # 8 # power
k = (1 + 3) * 2 # 8    # (expression) has higher priority

println("a: ", a)
println("b: ", b)
println("c: ", c)
println("d: ", d)
println("e: ", e)
println("f: ", f)
println("g: ", g)
println("h: ", h)
println("i: ", i)
println("j: ", j)
println("k: ", k)
Enter fullscreen mode Exit fullscreen mode

Output of this test:
Alt Text

Bitwise operations


# Bitwise operators: ~  &  | $ >>>  >>  <<
a = UInt8(5) 
b = UInt8(3) 
println("a: ", bitstring(a))
println("b: ", bitstring(b))
c = ~a 
println("c = ~a : ", bitstring(c))
d = a & b
println("d = a & b: ", bitstring(d))

e = a | b
println("e = a | b: ", bitstring(e))

f1 = a  b
f2 = xor(a, b)
println("f1 = a ⊻ b: ", bitstring(f1))
println("f2 = xor(a, b): ", bitstring(f2))

g = Int8(-7)  >>> 1  # logicalshift right
println("g = Int8(-7)  >>> 1: ", bitstring(g))
h = Int8(-7)  >> 1   # arithmetic shift right;
println("h = Int8(-7)  >> 1: ", bitstring(h))
i = UInt8(7)  << 1  # arithmetic shift left
println("i = UInt8(7)  << 1: ", bitstring(i))
Enter fullscreen mode Exit fullscreen mode

Output:
Alt Text

Boolearn operations

a = !true # false
b = !false # true
c = 1 == 1 # true
d = 2 == 1 # false
e = 1 != 1 # false
f = 2 != 1 # true
g = 1 < 10 # true
h = 1 > 10 # false
i = 2 <= 2 # true
j = 2 >= 2 # true
k = 1 < 2 < 3 # true
l = 2 < 3 < 2 # false
m, n, o = k  l, k & l, k | l

println("a: ", a)
println("b: ", b)
println("c: ", c)
println("d: ", d)
println("e: ", e)
println("f: ", f)
println("g: ", g)
println("h: ", h)
println("i: ", i)
println("j: ", j)
println("k: ", k)
println("l: ", l)
println("m: ", m)
println("n: ", n)
println("o: ", o)
Enter fullscreen mode Exit fullscreen mode

Output:
Alt Text

Top comments (0)

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay