Welcome to Julia!
Julia is a new language focused on technical and numerical computing, and similar to systems such as Octave (or MATLAB), IDL, SciLab, and Python+NumPy+SciPy.
Although Julia's current focus is technical computing, due to a well-considered design and an extensive mathematical library, Julia has also been used to write such things as web servers, and microframeworks, raytracers and a Quake rendering engine.
This tutorial is organized as follows:
Julia has been designed from the ground up for the needs of modern technical computing.
As a young, open-source language and community, there are nearly unlimited opportunities for contribution. The community strives to be welcoming to new contributors in any capacity. Some suggested areas to pursue contribution:
documentation: as with any open-source project, good documentation is critical for continued growth (and as such, contributions are deeply appreciated!)
packages: there are a huge number of "greenfield" packages just waiting to be written (or implemented in pure Julia). Come build something new, just the way you've always wanted it!
library: Because Julia's library is written in the language itself, the barrier-to-entry for contributions to the core repository is much lower than other projects written in a mix of languages. Pull requests are always welcome! Here is one list of potential areas to contribute.
core: the core of Julia is written in high-quality, terse, highly-readable C. Julia's code generation is written in C++ (with extern C
entry points) in order to interface with the LLVM JIT engine. There are many optimizations left to be written (for even better performance), and anyone with the skills and interest is welcome and encouraged to contribute.
We start with the canonical introductory program:
println("Hello, world!")
Hello, world!
Simple enough, right? Now, let's make a function:
function sayhello(name)
println("Hello, ", name)
end
sayhello (generic function with 1 method)
...and call it:
sayhello("friend!")
Hello, friend!
The "Hello, world" example could be written on the command line as:
julia -e 'println("Hello, world")
Or as a script, by placing the command in hello.jl
and running:
> julia hello.jl
To write text without appending a newline, use print()
:
print(1)
print(" 2")
1 2
This tutorial can be run in IJulia, and viewed statically using the IPython notebook viewer (IJulia is built on the remarkable IPython software)
In IJulia, each In [#]
line denotes an individual cell containing one or more lines of Julia code, which may be executed by pressing Shift-Enter
. Program output or errors will be displayed immediately below the input cell, and the return value of the last command in the cell will be printed in Out[#]
box.
In [1]: println("Hello, world!")
Hello, world! <-- standard output is captured and printed sans Out[] prefix.
In [3]: "Hello, friend!"
Out[3]: "Hello, friend!" <-- expression values are printed in the Out[] cell
i = 2.0
2.0
We can define complex variables using the special symbol im
denoting the imaginary unit:
e = 1+1im
1 + 1im
Julia contains a set of built-in constants, which may be used in computation or assigned to other variable names:
supercalifragilisticexpialidocious = pi
supercalifragilisticexpialidocious/2
1.5707963267948966
The cell above calculates pi/2
using the special variable supercalifragilisticexpialidocious that we have set as equal pi
, and prints the result to Out [ ]
.
You can even use names of built-in variables and functions, if you so choose. (This is usually not a good idea since it is very easy to write confusing code; Julia will warn you against overwriting built-ins, but will not stop you in this case)
You cannot, however, use the names of Julia keywords for your variable names.
end=0.5im
syntax: unexpected end at In[13]:1
supercalifragilisticexpialidocious == pi
true
pi == 3.2 # Sorry, Indiana
false
pi < 3.2
true
Inexact comparisons should use isapprox
isapprox(exp(im * pi) + 1, 0)
true
A single character is denoted with single-quote marks, and characters may be input by ASCII or Unicode value using the char
function:
'a' == char(97) # ASCII 97 is 'a'
true
Strings are denoted by double-quote signs, as in many other languages. Some characters may only be printed as escape sequences. An escape sequence starts with a backslash \
and ends with a single character that follows it.
Here are two very common examples:
println("1\n2") #Newline
1 2
println("1\t2") #Tab
1 2
To print the baskslash character itself, it must be escaped with another backslash.
println("1\\2") #backslash
1\2
The dollar sign has special meaning in Julia and must be escaped to print correctly.
println("\$")
$
What happens if we don't escape it?
println("$pi")
π = 3.1415926535897...
The dollar sign performs string interpolation, splicing the value of the variable name after the $
into the output. Attempting to splice a non-existent variable results in an error:
println("$α")
α not defined at In[20]:1
Julia supports Unicode for string contents as well as variable names. So variables:
α = 7.29735257E-3
0.00729735257
and formulae:
z = 3+4im
ξ = 1/z
0.09090909090909091
May be written with any appropriate character.
Or even using non-Latin alphabets!
アルコール = 0.1337
アルコール^2
0.017875690000000003
On some operating systems and browsers, you may even be able to print pizza!:
print(char(0x1f355))
print(" = ")
print('\U263A')
🍕 = ☺
Julia includes a Perl-compatible regular expression support. A regular expression is declared using the special syntax: r
prefixed immediately before the regex string:
re = r".*(brown fox).*(lazy dog)"
r".*(brown fox).*(lazy dog)"
m = match(re, "The quick brown fox jumped over the lazy dog.")
RegexMatch("The quick brown fox jumped over the lazy dog", 1="brown fox", 2="lazy dog")
m.captures[1]
"brown fox"
m.captures[2]
"lazy dog"
if false
println("Twilight zone...")
elseif ( 1 == 2 )
println("We can actually do math, right?")
else
println("All is well. Both conditions are false.")
end
All is well. Both conditions are false.
for i in 1:10
print(i, " ")
end
1 2 3 4 5 6 7 8 9 10
Breaking it down:
i in 1:10
returns an iterator over the range 1 to 10println
, we use simply print
, which does not add a newline after each outputWe can also skip elements using the continue
keyword:
for i in 1:10
(i > 5 && i < 9) && continue
print(i, " ")
end
1 2 3 4 5 9 10
Write the for loop above as a while loop instead.
So how do we get data out of and into Julia? Here is the simplest possible example:
# opening a file:
vecfile = open("/tmp/myvector.txt", "w")
IOStream(<file /tmp/myvector.txt>)
Notice that the open
function returns a variable with the type IOStream. This is important, because the behavior of other functions will be influenced by the type of this variable.
Write a function that prints the comma-separated numbers from 1 to 5, in increments of .5, to the file handle vecfile
defined above.
print
function is overloaded, and will accept an IOStream as the first argument.function writenumbers(fhandle)
# implementation goes here
end
writenumbers (generic function with 1 method)
writenumbers(vecfile)
Be sure to clean up the file handle:
close(vecfile)
Now that we have a file, let's read the data back in:
f_in = open("/tmp/myvector.txt", "r")
myvec1 = split( readall(f_in), "," )
10-element Array{String,1}: "1.0" "1.5" "2.0" "2.5" "3.0" "3.5" "4.0" "4.5" "5.0" ""
Since this is a CSV file, we could also use the built-in readcsv
function:
seekstart(f_in)
myvec1 = readcsv( f_in )
1x9 Array{Float64,2}: 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0
We have used the built-in function seekstart
to go back to the beginning of the file, so that we don't have to open it again.
Julia includes a number of useful data structures; here are two important examples:
Here we define a list containing a strange, heterogenous grab bag of stuff:
allmixedup = { 1, pi, "foo", myvec1, "biggles", sayhello }
6-element Array{Any,1}: 1 π = 3.1415926535897... "foo" 1x9 Array{Float64,2}: 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 "biggles" sayhello
Square brackets, [ ]
, are used to retrieve the contents at a specific index.
Note: Julia uses 1-based indexing just like Fortran. Everything will be ok.
allmixedup[1]
1
allmixedup[5]
"biggles"
allmixedup[6]
sayhello (generic function with 1 method)
As demonstrated above, can store a reference to a function like any other object!
List elements can be set by assigning to an index:
push!(allmixedup, "another random string")
7-element Array{Any,1}: 1 π = 3.1415926535897... "foo" [""] "biggles" sayhello "another random string"
call the sayhello
function by using the reference stored in allmixedup.
Julia provides an efficient associative array implementation and, like Python, there is a compact comprehension syntax to define a mapping set:
mymap = { 1 => "one", "two" => 2, "sayhello" => sayhello, sayhello => "function called `sayhello`"}
{"sayhello"=>sayhello,sayhello=>"function called `sayhello`",1=>"one","two"=>2}
(mymap
above accepts any type of object, but as will be seen, dictionary key and value types may be restricted)
Key-value pairs may also be assigned individually:
mymap[7.3] = "seven point 3"
"seven point 3"
Map indexing is similar to lists:
mymap[1]
"one"
mymap["two"]
2
mymap["sayhello"]
sayhello (generic function with 1 method)
mymap[sayhello]
"function called `sayhello`"
mymap[7.3]
"seven point 3"
Numbers are the soul of Julia, so it is fitting that all numeric types are defined in the language itself. For example, the 64-bit integer is declared as follows (in src/base/base.jl, for the curious):
bitstype 64 Int64 <: Signed
This means that you can define your own data types in pure Julia, and expect the same performance profile as "core" types!
One goal of Julia is to be fast enough that moving to another language for performance should never be necessary.
We can write numeric literals in binary representation:
0b10 == 2 # There are 10 kinds of programmers...
true
Julia is also quite willing to expose the when you want to see them. Binary representations are one example, and can be easily inspected:
[ 0 bits(0); 1 bits(1); 2 bits(2); 3 bits(3); 7 bits(7); 8 bits(8);
16 bits(16); 17 bits(17); 32 bits(32); 33 bits(33); 35 bits(35); 64 bits(64);]
12x2 Array{Any,2}: 0 "0000000000000000000000000000000000000000000000000000000000000000" 1 "0000000000000000000000000000000000000000000000000000000000000001" 2 "0000000000000000000000000000000000000000000000000000000000000010" 3 "0000000000000000000000000000000000000000000000000000000000000011" 7 "0000000000000000000000000000000000000000000000000000000000000111" 8 "0000000000000000000000000000000000000000000000000000000000001000" 16 "0000000000000000000000000000000000000000000000000000000000010000" 17 "0000000000000000000000000000000000000000000000000000000000010001" 32 "0000000000000000000000000000000000000000000000000000000000100000" 33 "0000000000000000000000000000000000000000000000000000000000100001" 35 "0000000000000000000000000000000000000000000000000000000000100011" 64 "0000000000000000000000000000000000000000000000000000000001000000"
Literal values without a decimal point are interpreted as integers:
x = 1
1
typeof(x)
Int64
Julia has both signed and unsigned Integer types for 8, 16, 32, 64, and 128-bits.
Each Integer type can hold a specific and finite range of values:
[ typemin(Uint8) typemax(Uint8) ;
typemin(Int8) typemax(Int8) ;
typemin(Int64) typemax(Int64) ; ]
3x2 Array{Int64,2}: 0 255 -128 127 -9223372036854775808 9223372036854775807
Literals entered with a decimal point are intepreted as floating-point numbers:
y = 2.0
2.0
[ 2. typeof(2.);
.5 typeof(.5); ]
2x2 Array{Any,2}: 2.0 Float64 0.5 Float64
Note that 0 == -0
, but they do not have the same binary representation:
0 == -0
true
[ " 0" bits(0.0) ;
"-0" bits(-0.0) ; ]
2x2 Array{ASCIIString,2}: " 0" "0000000000000000000000000000000000000000000000000000000000000000" "-0" "1000000000000000000000000000000000000000000000000000000000000000"
Julia does arithmetic using machine numbers which can represent only finite ranges and with finite precision (as compared to the idealized $\mathbb{R}$eal numbers). The eps
function returns the smallest difference that can be represented by a given type:
[ 1.0 bits(1.0)
repr(1.0 + eps(1.0)) bits(1.0 + eps(Float64)) ]
2x2 Array{Any,2}: 1.0 … "0011111111110000000000000000000000000000000000000000000000000000" "1.0000000000000002" "0011111111110000000000000000000000000000000000000000000000000001"
Exceeding the maximum representable type (typemax
) for a given type results in wrap-around:
typemax(Int64)
9223372036854775807
typemax(Int64) + 1
-9223372036854775808
For more information on numerical representations and accurate computation with machine math, please see the excellent discussion in the Julia manual (and links therein).
As seen earlie, the imaginary unit is called im
in Julia.
z=3+4im
3 + 4im
After defining a complex variable, addition and multiplication "just work":
z+z
6 + 8im
z*z' # z' denotes the conjugate of z (complex, of course)
25 + 0im
Operations on heterogenous types result in promotion to the most representative common type:
x + y
3.0
typeof(x + y)
Float64
0x1 + 2
3
[ typeof(0x1) typeof(0x1 + 2) ]
1x2 Array{DataType,2}: Uint8 Int64
For the sake of completeness, here is a review of all of the standard arithmetic operators:
rtmc = [ 1+1 -2 1/2 2/3 3\2 2^3 x%y y^4 ]
1x8 Array{Float64,2}: 2.0 -2.0 0.5 0.666667 0.666667 8.0 1.0 16.0
The rtmc
assignment above is an example of array declaration, with array elements computed in place using the specified inputs and operations.
Again, Julia converts all operations to the most representative type for given arguments. For example, division between integers results in a floating point number:
[ 2/3 typeof(2/3) ]
1x2 Array{Any,2}: 0.666667 Float64
This rule is applied consistently even if the result could be represented exactly by the common type of the input variables:
[ 4/2 typeof(4/2) ]
1x2 Array{Any,2}: 2.0 Float64
Let's look at several compact ways to create an array, noting in particular the use of array comprehension:
a = ones(5)
5-element Array{Float64,1}: 1.0 1.0 1.0 1.0 1.0
b = [ 5:9 ] # 5-9, inclusive
5-element Array{Int64,1}: 5 6 7 8 9
c = eye(4) # returns the 4x4 identity matrix
4x4 Array{Float64,2}: 1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0
d = ones(4,4) # returns a 4x4 matrix of ones
4x4 Array{Float64,2}: 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0
We can do arithmetic with array elements:
a[1] + b[1]
6.0
And with entire arrays, such as addition:
a + b
5-element Array{Float64,1}: 6.0 7.0 8.0 9.0 10.0
... scalar multiplication:
5 * b
5-element Array{Int64,1}: 25 30 35 40 45
... and exponentiation:
b .^ 2
5-element Array{Int64,1}: 25 36 49 64 81
This last one is important: the .^
operator denotes element-wise operation. As a general convention in Julia, element-wise operators are denoted with a dot prefixed to the operator symbol.
Julia has a powerful type system, and variables carry type information that is automatically inferred at the time of assignment (and helpfully printed by IJulia):
rtmc = [ 1 1+1 -2 1/2 2/3 3\2 2^3 x%y y^4 ]
1x9 Array{Float64,2}: 1.0 2.0 -2.0 0.5 0.666667 0.666667 8.0 1.0 16.0
Although it is fully possible to program in Julia without explicit type declarations, the type system is fundamental to higher-level and generic programming. Let's make a quick review of some types encountered so far:
typeof('a')
Char
typeof("Quick brown fox")
ASCIIString (constructor with 1 method)
typeof(1)
Int64
typeof(1.0)
Float64
typeof([1.0 2.0 3.0])
Array{Float64,2}
typeof([ 1 => "2", 2 => "2"])
Dict{Int64,ASCIIString} (constructor with 2 methods)
typeof(allmixedup)
Array{Any,1}
This last one is special: the Any
type is the root of the type hierarchy in Julia.
We can explicitly specify the accepted key-value types in a dictionary constructor:
int_to_string = Dict{Int,String}()
Dict{Int64,String}()
Or, we can ask Julia to select inferred types by using square bracket [ ]
comprehension instead of the curly bracket { }
comprehension used earlier:
int_to_string = [ 1 => "1", 2 => "2"]
[2=>"2",1=>"1"]
typeof(int_to_string)
Dict{Int64,ASCIIString} (constructor with 2 methods)
Assigning an Integer-String pair works:
int_to_string[3] = "foo"
"foo"
But, unsurprisingly, assigning a String-String pair does not:
int_to_string["item3"] = "baz"
no method convert(Type{Int64},ASCIIString) at In[91]:1 in setindex! at dict.jl:412
These last lines failed becase int_to_string
expects only Integers as keys, and only strings as values.
Julia provides a mechanism to define custom composite (aggregate) types, reminescent of structs in C, and plain-old-data classes in C++.
type LP
c # Types are optional
A::Matrix{Float64}
b::Vector{Float64}
end
randlp(n,m) = LP(rand(n),rand(n,m),rand(m))
mylp = randlp(10,5)
println(mylp.c)
.41658206875707227 .5017688328770391 .4950271332072449 .47894020363889234 .4810285428763976 .5129626979895638 .4894621516145241 .04926848192609756 .35015060687983346 .57393984978873
Warning: imported binding for Int64 overwritten in module Main
Parametric types take one (or more) type arguments which are used in the final construction of constituent fields:
type LP2{T}
c::Vector{T}
A::Matrix{T}
b::Vector{T}
end
We can construct derived types by specifying the element type in the constructor, between { }
curly brackets following the type name:
lp = LP2{Float64}(mylp.c,mylp.A,mylp.b) # dbl precision
LP2{Float64}([0.41658206875707227,0.5017688328770391,0.4950271332072449,0.47894020363889234,0.4810285428763976,0.5129626979895638,0.4894621516145241,0.04926848192609756,0.35015060687983346,0.57393984978873],10x5 Array{Float64,2}: 0.31356 0.421467 0.855788 0.184812 0.522469 0.523827 0.000162772 0.80338 0.990524 0.435689 0.903068 0.412541 0.208929 0.249097 0.0109994 0.73804 0.00372301 0.880434 0.287483 0.962761 0.41663 0.475956 0.716943 0.748487 0.642943 0.561952 0.594682 0.408093 0.375726 0.554211 0.428398 0.390269 0.264798 0.655475 0.473286 0.759091 0.60214 0.232885 0.922757 0.946042 0.179187 0.204381 0.995682 0.0101273 0.592077 0.674353 0.806467 0.180198 0.677089 0.871963 ,[0.599648906039072,0.5608212204969416,0.9780278280294874,0.11913449426512002,0.2961395431294518])
Recall the IJulia output after the definition of sayhello
in the first section:
In [146]: function sayhello(name)
println("Hello, ", name)
end
Out[146]: sayhello (generic function with 1 method)
Notice the line (generic function with 1 method)
.
What happens if we define another version of this function with a different argument type?
sayhello(friendnumber::Number) = println("Hello, numerical friend ", friendnumber)
sayhello (generic function with 2 methods)
Aha! No error. Instead, IJulia tells us that sayhello
now refers to a function with two methods. Compare the output when we call this function with different types of arguments:
sayhello("Bob")
Hello, Bob
sayhello(3)
Hello, numerical friend 3
sayhello(4.0)
Hello, numerical friend 4.0
When we call sayhello
with a String argument, the original definition with unspecified type is used. When we call sayhello
with any numerical type, the new Number-specific version is called.
We can make another, even more specific definition; compare the output now with different argument types:
sayhello(fpfriend::FloatingPoint) = println("Hello, floating point friend ", fpfriend)
sayhello (generic function with 3 methods)
sayhello(4)
Hello, numerical friend 4
sayhello(5.0)
Hello, floating point friend 5.0
Why does this work? Julia's multiple dispatch chooses the most specific method for a given argument. Float64
is a subtype of Number
(twice removed), so the Float64
version is used for a floating point argument, but the earlier Number
version is still used for other numeric types.
Float64
is a subtype of the abstract FloatingPoint
type:
super(Float64)
FloatingPoint
which is in turn a subtype of Number
:
issubtype(Float64, Number)
true
Write a function to print the type hierarchy for a given type. Hint: use the super
function as shown above.
function hierarchy(t::Type)
end
hierarchy (generic function with 1 method)
hierarchy(Int64)
Expected output:
In[]: hierarchy(Int64)
Signed
Integer
Real
Number
Any
We can use type annotated functions to define different behavior for various types of arrays:
function array_sum(x::Array{Float64, 1})
y = 0
for i in 1:length(x)
y += x[i] + 2
end
return y
end
function array_sum(x::Array{Int64, 1})
y = 0
for i in 1:length(x)
y += x[i] + 1
end
return y
end
array_sum (generic function with 2 methods)
array_sum([ 1, 2, 3, 4, 5 ]) # array of integers
20
array_sum([ 1.0, 2, 3, 4, 5 ]) # array of floats
25.0
function vec_norm(ar::Array{Float64,1})
end
vec_norm (generic function with 1 method)
Expected output
In [8]: vec_norm([1.0, 1.0, 1.0])
Out[8]:
3-element Array{Float64,1}:
0.57735
0.57735
0.57735
Julia provides a facility to call C (and Fortran!) libraries with no runtime overhead.
path = ccall( (:getenv, "libc"), Ptr{Uint8}, (Ptr{Uint8},), "PATH")
Ptr{Uint8} @0x00007fff4dc88553
bytestring(path)
"/home/isaiah/bin:/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games"
using PyPlot
x = -3pi:.01:3pi
plot(x, sin(x))
1-element Array{Any,1}: PyObject <matplotlib.lines.Line2D object at 0xa8a2550>
Julia supports two kinds of code blocks. The first is delimited by:
begin
# and
"hello"
end
"hello"
And the second is delimted by parentheses, with expressions separated by a semi-colon ;
between each expression:
expression = 1
( this = 1; is = 2; println(a[1]); valid = expression )
1.0
1
The final expression in a code block determines the resulting value, if any. Code blocking style can be used to great effect
Julia provides access to several levels of transformed code between the initial input and the executable, including type-annotated expressions, LLVM Intermediate Representation, and finally the resulting machine code for any function.
function plus(x::Float64, y::Float64)
return x + y
end
plus (generic function with 1 method)
code_typed(plus, (Float64, Float64))
1-element Array{Any,1}: :($(Expr(:lambda, {:x,:y}, {{},{{:x,Float64,0},{:y,Float64,0}},{}}, quote # In[114], line 2: return top(box)(Float64,top(add_float)(x::Float64,y::Float64))::Float64 end)))
code_llvm(plus, (Float64, Float64))
define double @julia_plus(double, double) { top: %2 = fadd double %0, %1, !dbg !15456 ret double %2, !dbg !15456 }
code_native(plus, (Float64, Float64))
.text Filename: In[114] Source line: 2 push RBP mov RBP, RSP Source line: 2 vaddsd XMM0, XMM0, XMM1 pop RBP ret