Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 40 Β· Basics

Numbers and Math

Learn Julia numeric types: Int64, Float64, Rational, Complex and BigInt, literals, division with div and rem, integer overflow and the ^ and .^ operators.

Julia was built for numerical work, so its numbers are more capable than in most languages. Integers and floats come in several sizes, fractions and complex numbers are built in, and arbitrary-precision types are one function call away. In this lesson you will learn the main numeric types, the literals that create them, the arithmetic operators (with some Julia-specific twists) and the one trap every systems-style language has: integer overflow.

Julia code on this page is read-only with its output in comments. Python stand-ins let you reproduce the ideas, such as wrap-around overflow and exact fractions.

The common types

JULIA
typeof(42)        # Int64
typeof(3.14)      # Float64
typeof(1//3)      # Rational{Int64}
typeof(2 + 3im)   # Complex{Int64}
typeof(true)      # Bool
  • Int64 is the default integer on a 64-bit machine. Smaller and larger relatives exist: Int8, Int16, Int32, Int128 and their unsigned versions UInt8 and so on.
  • Float64 is the default floating-point number (double precision). Float32 and Float16 also exist.
  • Rational stores an exact fraction, and Complex stores a real and an imaginary part.
  • BigInt and BigFloat hold values of any size, at a speed cost.

These types sit in a hierarchy under Number, as you saw in The Type System.

Literals

JULIA
1_000_000      # underscores make long numbers readable
0x1F           # 31, hexadecimal (this is a UInt8)
0b1010         # 10, binary
0o17           # 15, octal
1e3            # 1000.0, scientific notation is a Float64
1.5f0          # Float32
2.5e-4         # 0.00025

A literal without a decimal point is an integer, and with a decimal point or an e exponent it is a float. Note that 1e3 is 1000.0, a float, not an integer.

Coefficient syntax lets you write products the way mathematics does. A number placed directly before a variable or parenthesis multiplies it:

JULIA
x = 4
2x          # 8
3(x + 1)    # 15
2Ο€          # 6.283185307179586

Arithmetic operators

JULIA
7 + 3     # 10
7 - 3     # 4
7 * 3     # 21
7 / 2     # 3.5   (always a floating-point result)
7 ^ 2     # 49    (power)
7 % 3     # 1     (same as rem)
7 Γ· 2     # 3     (integer division, same as div; type \div then Tab)

Two details are worth remembering. First, / between integers gives a float. Second, ^ binds tighter than unary minus on the left: -2^2 is -4.

div, rem, fld and mod

Dividing negative numbers has two reasonable conventions, so Julia provides both:

JULIA
div(-7, 2)    # -3   truncates toward zero
rem(-7, 2)    # -1   remainder matching div
fld(-7, 2)    # -4   floors toward negative infinity
mod(-7, 2)    # 1    remainder matching fld (result has the divisor's sign)

The relationship is x == div(x, y) * y + rem(x, y) for the first pair and x == fld(x, y) * y + mod(x, y) for the second. % is rem, so -7 % 2 is -1. For clock arithmetic and array wrap-around you almost always want mod.

Comparison and equality

JULIA
3 == 3.0      # true   (values are equal)
3 === 3.0     # false  (not identical: different types)
1 < 2 <= 2    # true   (chains work like in math)
0.1 + 0.2 == 0.3          # false
isapprox(0.1 + 0.2, 0.3)  # true, also written 0.1 + 0.2 β‰ˆ 0.3

Floating-point numbers are binary approximations, so compare them with isapprox (β‰ˆ, typed \approx then Tab) instead of ==. This is true in every language, not only Julia.

Rational and complex numbers

The // operator creates an exact fraction that is automatically reduced:

JULIA
r = 3//4
r + 1//4         # 1//1
2//4             # 1//2
numerator(r)     # 3
denominator(r)   # 4
float(r)         # 0.75

Complex numbers use im for the imaginary unit:

JULIA
z = 3 + 4im
real(z)      # 3
imag(z)      # 4
abs(z)       # 5.0
conj(z)      # 3 - 4im
z * z        # -7 + 24im
sqrt(Complex(-1))   # 0.0 + 1.0im

Notice sqrt(-1) on a plain integer throws a DomainError instead of returning a complex number. That is deliberate: it keeps the return type predictable, which helps the compiler. Ask for the complex result explicitly with Complex(-1).

Integer overflow

Fixed-size integers wrap around silently when they exceed their range. This is fast, but surprising:

JULIA
typemax(Int64)        # 9223372036854775807
typemax(Int64) + 1    # -9223372036854775808  (wraps to typemin)
2^62                  # 4611686018427387904
2^63                  # -9223372036854775808
2^64                  # 0

There is no error. The result simply keeps the low 64 bits. A famous consequence is factorial(21), which is too large for Int64: the standard factorial function checks and throws an OverflowError instead of returning nonsense, but your own loops will not.

You have three ways to be safe:

  1. Use BigInt for exact arbitrary-size integers: big(2)^100 is 1267650600228229401496703205376.
  2. Use checked arithmetic: Base.checked_add(typemax(Int64), 1) throws OverflowError.
  3. Use Float64 when approximate values are fine.

The following stand-in reproduces wrap-around by keeping the low 64 bits of a Python integer and converting to signed. Python's own integers never overflow, so this is an explicit imitation.

Python 64-bit wrap-around (analogy)

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The printed values match what Julia's Int64 produces. Julia's BigInt behaves like Python's default int.

Powers and broadcasting with .^

^ is the power operator for a single number. On a matrix, A^2 means the matrix product A * A. To raise every element of an array to a power, use the dotted form .^, an example of broadcasting that you will study in Broadcasting and the Dot Syntax:

JULIA
v = [1, 2, 3]
v .^ 2          # [1, 4, 9]
2 .^ v          # [2, 4, 8]

A = [1 2; 3 4]
A ^ 2           # [7 10; 15 22]   matrix product A*A
A .^ 2          # [1 4; 9 16]     element-wise square

Integer powers with negative exponents need care. 2^-1 throws a DomainError because the exact result is not an integer. Use 2.0^-1 (which gives 0.5) or 1//2.

Pick the right number type

Int64 Fast whole numbers. Wraps on overflow.
Float64 Fast, approximate decimals.
Rational Exact fractions like 3//4.
BigInt Any size, slower.

Complex numbers use im, as in 3 + 4im.

1 / 2

Python supplies a faithful stand-in for exact fractions and complex numbers. This one reproduces the div, rem, fld and mod table with the matching Python operators.

Python Rational, complex and remainders

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In Python // and % floor like Julia's fld and mod, while math.trunc and math.fmod truncate like div and rem. Julia's names make the choice explicit.

Useful math functions

JULIA
sqrt(16)          # 4.0
abs(-5)           # 5
round(2.567, digits=2)   # 2.57
floor(Int, 2.9)   # 2
ceil(Int, 2.1)    # 3
min(3, 7)         # 3
max(3, 7)         # 7
exp(1)            # 2.718281828459045
log(β„―)            # 1.0
sin(Ο€ / 2)        # 1.0
gcd(12, 18)       # 6
lcm(4, 6)         # 12

log is the natural logarithm, log10 and log2 are the others. Trigonometric functions use radians, and variants such as sind use degrees.

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. What is typeof(7 / 2)?

    / always returns a floating-point number. The exact quotient 7//2 would be a Rational, and div(7, 2) the integer 3.
  2. 2. What does typemax(Int64) + 1 give?

    Fixed-size integer arithmetic wraps around silently, so the result is typemin(Int64). Use BigInt or checked arithmetic when that matters.
  3. 3. What is mod(-7, 2)?

    mod matches floored division (fld(-7, 2) is -4), so the remainder is -7 - (-4 * 2) = 1. rem(-7, 2) would be -1.
  4. 4. Which expression squares every element of the vector v?

    The dot makes the power operator work element by element. v ^ 2 is a MethodError for a vector, since matrix power needs a square matrix.
  5. 5. How should you compare 0.1 + 0.2 with 0.3?

    Floating-point values are approximations, so == returns false here. isapprox or β‰ˆ tests closeness within a tolerance.

Summary

  • The defaults are Int64 and Float64; Rational, Complex, BigInt and BigFloat extend them.
  • Literals: 1_000, 0xFF, 0b101, 1e3 (a float), 3//4, 2 + 3im; 2x means 2 * x.
  • / is float division; div and Γ· truncate, fld floors, rem and % pair with div, mod pairs with fld.
  • Fixed-size integers wrap around on overflow without any error; use BigInt when needed.
  • Compare floats with isapprox (β‰ˆ).
  • ^ is a power (or a matrix power), while .^ works element by element.

Next, turn to text in Strings and Characters.