Skip to content
AgileLogics
6 min read

Numbers and Arithmetic

Prerequisites: Variables

Julia has separate types for whole numbers (integers) and numbers with a fractional part (floating-point):

println(typeof(42))
println(typeof(3.14))
println(7 + 2, " ", 7 - 2, " ", 7 * 2)
println(7 / 2)
println(7 ÷ 2, " ", div(7, 2))
println(7 % 2, " ", rem(7, 2))
println(2^10)
println(-7 ÷ 2, " ", fld(-7, 2), " ", mod(-7, 2))
Int64
Float64
9 5 14
3.5
3 3
1 1
1024
-3 -4 1
  • / always gives a float, even for 6 / 3.
  • ÷ (type \div + Tab) or div is integer division, rounding toward zero; fld rounds down. % is the remainder and mod the mathematical modulus — they differ for negative numbers.
  • ^ is exponentiation.

Math that reads like math

x = 3
println(2x + 1)
println(3x^2 - 2x)
println(sqrt(16), " ", abs(-5), " ", round(2.567, digits=2))
println(floor(Int, 3.7), " ", ceil(Int, 3.2), " ", round(Int, 2.5))
println(max(3, 9, 4), " ", min(3, 9, 4))
println(exp(0), " ", log(ℯ), " ", sin(π / 2))
7
21
4.0 5 2.57
3 4 2
9 3
1.0 1 1.0
  • A number directly before a variable multiplies it: 2x is 2 * x.
  • round(Int, 2.5) gives 2: Julia rounds halves to the nearest even number by default (banker's rounding).
  • π and ℯ (type \euler + Tab) are built-in constants.

Integer overflow

Integers have a fixed size (Int64 on 64-bit computers) and silently wrap around when they overflow — fast, but surprising:

println(typemax(Int64))
println(typemax(Int64) + 1)
println(2^64)
println(big(2)^64)
println(factorial(big(25)))
9223372036854775807
-9223372036854775808
0
18446744073709551616
15511210043330985984000000

Use big(...) to get a BigInt (arbitrary size) when numbers can grow large.

Floats, rationals, and complex numbers

println(0.1 + 0.2)
println(0.1 + 0.2 == 0.3)
println(isapprox(0.1 + 0.2, 0.3))
println(0.1 + 0.2 ≈ 0.3)
println(1 // 3 + 1 // 6)
println((1 + 2im) * (3 - im))
println(1 / 0, " ", -1 / 0, " ", 0 / 0)
0.30000000000000004
false
true
true
1//2
5 + 5im
Inf -Inf NaN
  • Floats are approximate, so compare them with ≈ (\approx + Tab) or isapprox, not ==.
  • // makes an exact rational number; im is the imaginary unit.
  • Float division by zero gives Inf or NaN instead of an error.

Practice

Compute the area of a circle with radius 2.5 (π * r^2), and print it rounded to 3 decimal places. Then print how many whole minutes and leftover seconds are in 500 seconds.

Show solution
r = 2.5
println(round(π * r^2, digits=3))
total = 500
println(total ÷ 60, " min ", total % 60, " s")
19.635
8 min 20 s