A Julia tutorial

If you can read this and see the IJulia logo in the top left corner of the browser window, congratulations! You are ready to start using Julia.

This IJulia notebook is fully executable. The Julia code is grouped into units called cells. To run all the commands in a cell, click inside and press Shift+Enter.


In [ ]:
1+1

Try changing the code to see what it will do!

1. Printing things

The basic way to print things is to use the println() (print line) function.


In [2]:
println("Hello world")


Hello world

You can also use the print() function, which does the same thing, but leaves out the newline at the end.


In [3]:
print("Hello")
print("world")


Helloworld

Don't forget the enclosing parentheses, or you will get an error:


In [16]:
print 1+2


syntax: extra token "1" after end of expression
at In[16]:1

In [17]:
print(1+2)


3

You can print multiple things together. Separate each piece with commas:


In [19]:
print("1 + 1 = ", 1+1)


1 + 1 = 2

Note: Julia does not automatically insert spaces when printing multiple items together:


In [23]:
println("For","sooth!","There is no ",1," I trust more", ".")


Forsooth!There is no 1 I trust more.

Printing in interactive mode

In a REPL such as this IJulia notebook, Julia will automatically print the result of the last statement. This will not happen if you run julia in a non-interactive mode.


In [24]:
1+1
2+2


Out[24]:
4

However, a print or println function will always produce printable output.


In [26]:
1
2
print("3")
4
5


3
Out[26]:
5

Escaping characters

Some special characters are produced by escape sequences. An escape sequence starts with a backslash \ and ends with a single character that follows it.

Here are two very common examples:


In [53]:
println("1\n2") #Newline
println("1\t2") #Tab


1
2
12
1	2

To print the baskslash character itself, it has to be escaped with another backslash.


In [54]:
println("1\\2") #backslash


1\2

The dollar sign has special meaning in Julia and must be escaped to print correctly.


In [74]:
println("\$")


$

(Optional) Unicode characters

Julia supports Unicode characters, which are used to encode non-English texts and special symbols.


In [15]:
println('∑')


In Julia, a single character is quoted with single quotes ('), whereas strings are enclosed by double quotes (").

The following will produce an error in Julia:


In [8]:
println('Hello')


syntax: invalid character literal
at In[8]:1

Here is the first article of the UN Declaration of Human Rights in Chinese:


In [6]:
print("人人生而自由,在尊严和权利上一律平等。他们赋有理性和良心,并应以兄弟关系的精神相对待。")


人人生而自由,在尊严和权利上一律平等。他们赋有理性和良心,并应以兄弟关系的精神相对待。

To specify a Unicode character by its code point:

a) use \U followed by its hexadecimal code point.


In [12]:
print('\U263A')


or, b) use the char() function.


In [2]:
char(0xa22d)


Out[2]:
'ꈭ'

In [ ]:
Julia provides the `is_valid_char()` function to check if a valid character was specified.

In [1]:
println(is_valid_char(0x110000))
println(is_valid_char(0x1100))


Starting kernel event loops.
false
true

Sometimes the character won't display correctly. This is usually a problem with the font you are using.

You can try your luck with the Unicode character for a slice of pizza:


In [33]:
println('\U1f355')


🍕

2. Comments

Julia ignores the entire part of a line after a # symbol. (What is this symbol [really called](http://en.wiktionary.org/wiki/octothorpe) anyway?)</small></small>


In [28]:
print("The jail still held the heart I lost and the finger I stole") #from you


The jail still held the heart I lost and the finger I stole

(This example sentence was taken from [here](http://www.essayscam.org/Forum/17/ellipsis-4109/).)</small></small>

Comments are useful for leaving notes about code that is tricky or potentially confusing, and for temporarily disabling part of Julia programs.


In [31]:
println("Roses are red")
println("Violets are blue")
#println("I don't like bread")
println("One plus one is ", 1+1) #Compute the answer


Roses are red
Violets are blue
One plus one is 2

3. Basic math

Here's the very basics.


In [40]:
println("+1 = ", +1)
println("-1 = ", -1)
println("1 + 1 = ", 1+1)
println("1 - 1 = ", 1-1)
println("2 * 3 = ", 2*3)
println("2 / 3 = ", 2/3)  #The answer is not a whole number!
println("3 \\ 2 = ", 3\2) #Same as above
println("2 ^ 3 = ", 2^3)  #This is exponentiation


+1 = 1
-1 = -1
1 + 1 = 2
1 - 1 = 0
2 * 3 = 6
2 / 3 = 0.6666666666666666
3 \ 2 = 0.6666666666666666
2 ^ 3 = 8

Remainders are slightly trickier, particularly when it comes to negative numbers.


In [58]:
println("5 % 2 = ", 5%2)
println("rem(5,2) = ", rem(5,2)) #Same as above
println("mod(5,2) = ", mod(5,2))


5 % 2 = 1
rem(5,2) = 1
mod(5,2) = 1

In [64]:
println("5 % 2.5 = ", 5%2.5)
println("rem(5,2.5) = ", rem(5,2.5)) #Same as above
println("mod(5,2.5) = ", mod(5,2.5))


5 % 2.5 = 0.0
rem(5,2.5) = 0.0
mod(5,2.5) = 0.0

In [59]:
println("-5 % 2 = ", -5%2)
println("rem(-5,2) = ", rem(-5,2)) #Same as above
println("mod(-5,2) = ", mod(-5,2))


-5 % 2 = -1
rem(-5,2) = -1
mod(-5,2) = 1

For convenience, you can use underscores (_) to separate groups of digits.


In [12]:
525_600 #Five hundred twenty five thousand six hundred


Out[12]:
525600

In [11]:
1_00_00_000 #One crore = 10^7


Out[11]:
10000000

TODO Floating-point


In [65]:
println("1 / 0 = ", 1/0)


1 / 0 = Inf

Complex numbers

The imaginary unit is called im in Julia.


In [6]:
z=3+4im
z' #conjugate


Out[6]:
3 - 4im

In [8]:
z*z'


Out[8]:
25 + 0im

4. Variables

Variables allow you to store and reuse the results from earlier calculations.

There are very few limits to what names you can use for your variables. There is no implicit type of any variable.

Naming variables and Assigning them values

Use a single equal = sign to assign variables.


In [13]:
i=2.0


Out[13]:
2.0

In [15]:
supercalifragilisticexpialidocious = pi
supercalifragilisticexpialidocious/2


Out[15]:
1.5707963267948966

In [17]:
e = 1+1im


Out[17]:
1 + 1im

In [27]:
z=3+4im
ξ=1/z


Out[27]:
0.09090909090909091

In [30]:
アルコール = 0.1337
アルコール^2


Out[30]:
0.017875690000000003

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.)


In [31]:
im=2
3+4im


Out[31]:
11

You cannot, however, use the names of Julia keywords for your variable names.


In [23]:
end=0.5im


syntax: unexpected end
at In[23]:1

Comparing variables

Use the double equals == operator to compare variables or values.


In [33]:
x=1
x==2


Out[33]:
false

To test inequality, use !=:


In [35]:
x!=x+1


Out[35]:
true

In [ ]:
Printing variables

In [ ]:
There are a few ways to print variables in Julia:

In [ ]:
g=9.81

Multiple dispatch


In [ ]:


In [1]:
f(x::Number, y::Number) = (x,y)
f(1,2)


Out[1]:
(1,2)

In [2]:
f(x::String, y::String) = string(x,y)
f("foo","bar")


Out[2]:
"foobar"

In [4]:
f(x,y) = f(string(x),string(y))
f("I like ",1π)


Out[4]:
"I like 3.141592653589793"

Introspection


In [5]:
methods(f)


Out[5]:
# 3 methods for generic function "f":
f(x::Number,y::Number) at In[1]:1
f(x::String,y::String) at In[2]:1
f(x,y) at In[4]:1

Declaring types


In [6]:
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)


.23562710945428877
.23951372465002896
.7525737066697606
.010800546955753054
.5230908626626509
.2716179537331287
.7217869017869374
.8982447615369507
.5718451267150129
.5881888772951562

Parametric types


In [9]:
type LP2{T}
    c::Vector{T}
    A::Matrix{T}
    b::Vector{T}
end


invalid redefinition of constant LP2
at In[9]:5

In [10]:
lp = LP2{Float64}(mylp.c,mylp.A,mylp.b) # dbl precision
lp = LP2{Rational}(mylp.c,mylp.A,mylp.b) # exact


no method LP2{Rational{T<:Integer}}(Array{Float64,1},Array{Float64,2},Array{Float64,1})
at In[10]:2

Lists


In [11]:
L = {}             # empty Vector{Any}
push!(L,3.0)


Out[11]:
1-element Array{Any,1}:
 3.0

In [12]:
L2 = Float64[]     # Vector{Float64}
push!(L2,:Hello)   # Error


no method convert(Type{Float64},Symbol)
at In[12]:2
 in push! at array.jl:659

In [13]:
push!(L2,10.7)     # Okay


Out[13]:
1-element Array{Float64,1}:
 10.7

In [14]:
L3 = Float64[2,3,4]# conversion


Out[14]:
3-element Array{Float64,1}:
 2.0
 3.0
 4.0

Dictionaries


In [15]:
d1 = Dict()           # Empty untyped
d1[key] = 10        # Okay


“key” not defined
at In[15]:2

In [17]:
d2 = (Symbol=>Int)[]  # Empty typed
d2[:x] = 8            # Okay
d2[10] = "value"      # Error


no method convert(Type{Symbol},Int64)
at In[17]:3
 in setindex! at dict.jl:412

In [19]:
d3 = [:Cat=>13, :Dog=>14]
d3[:Dog]


Out[19]:
14

Exercise!

Write a function that takes a vector and normalizes it in place by its L2 norm. Use for loops.


In [20]:
f(v) = v/norm(v)


Out[20]:
f (generic function with 4 methods)

In [ ]:


In [ ]: