Julia Tutorial
Julia Tutorial
1
Julia Programming
The Julia programming language fulfill these expectations. It is a general purpose high-
performance flexible programming language which can be used to write any applications.
It is well-suited for scientific and numerical computing.
Audience
This tutorial will be useful for graduates, post-graduates, and research students who either
have an interest in Julia Programming or have these subjects as a part of their curriculum.
The reader can be a beginner or an advanced learner.
Prerequisites
The reader should have knowledge on basic computer programming languages.
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at contact@tutorialspoint.com
2
Julia Programming
Table of Contents
About the Tutorial ........................................................................................................................................... 2
Audience .......................................................................................................................................................... 2
Prerequisites .................................................................................................................................................... 2
Packages ........................................................................................................................................................ 16
Variables ........................................................................................................................................................ 22
Comments ..................................................................................................................................................... 23
3
Julia Programming
Integers .......................................................................................................................................................... 45
Arithmetic Operators..................................................................................................................................... 55
Rounding functions........................................................................................................................................ 64
Characters...................................................................................................................................................... 75
Interpolation .................................................................................................................................................. 79
Map ............................................................................................................................................................... 88
Filter .............................................................................................................................................................. 89
Ternary expressions....................................................................................................................................... 91
Loop variables................................................................................................................................................ 94
Comprehensions ............................................................................................................................................ 97
9
1. Julia — Overview Julia Programming
History of Julia
Let us see the history of Julia programming language in the following points:
Jeff Bezanson, Stefan Karpinski, Viral B. Shah, and Alan Edelman has started to
work on Julia in 2009.
The developer’s team of above four has launched a website on 14 th February 2012.
This website had a blog post primarily explaining the mission of Julia programming
language.
Later in April 2012, Stefan Karpinski, in an interview with a magazine named
InfoWorld, gave the name “Julia” for their programming language.
In 2014, the annual academic conference named ‘The JuliaCon’ for Julia; users
and developers has been started and since then it was regularly held every year.
In August 2014, Julia Version 0.3 was released for use.
In October 2015, Julia Version 0.4 was released for use.
In October 2016, Julia Version 0.5 was released for use.
In June 2017 Julia Version 0.6 was released for use.
Julia Version 0.7 and Version 1.0 were both released on the same date 8 th August
2018. Among them Julia version 0.7 was particularly useful for testing packages as
well as for the users who wants to upgrade to version 1.0.
10
Julia Programming
Julia versions 1.0.x are the oldest versions which are still supported.
In January 2019, Julia Version 1.1 was released for use.
In August 2019, Julia Version 1.2 was released for use.
In November 2019, Julia Version 1.3 was released for use.
In March 2020, Julia Version 1.4 was released for use.
In August 2020, Julia Version 1.5 was released for use.
Features of Julia
Following are some of the features and capabilities offered by Julia:
Prototyping: Prototyping is one such problem in technical computing discipline that needs
a high-level and flexible programming language so that the developer should not worry
about the low-level details of computation and the programming language itself.
Speed: Another important issue in technical domain is the speed. Before Julia, the
programmers need to have mastery on both high-level programming (for writing code in
Matlab, R, or, Python for prototyping) and low-level programming (writing performance-
11
Julia Programming
Following is the detailed comparison of Julia with the most used programming languages
— Matlab, R, and Python:
MATLAB: The syntax of Julia is similar to MATLAB, however it is a much general purpose
language when compared to MATLAB. Although most of the names of functions in Julia
resemble OCTAVE (the open source version of MATLAB), the computations are extremely
different. In the field of linear algebra, Julia has equally powerful capabilities as that of
MATLAB, but it will not give its users the same license fee issues. In comparison to
OCTAVE, Julia is much faster as well. MATLAB.Jl is the package with the help of which
Julia provides an interface to MATLAB.
Python: Julia compiles the Python-like code into machine code that gives the programmer
same performance as C programming language. If we compare the performance of Julia
and Python, Julia is ahead with a factor of 10 to 30 times. With the help of PyCall package,
we can call Python functions in Julia.
R: As we know, in statistical domain, R is one of the best development languages, but with
a performance increase of a factor of 10 to 1,000 times, Julia is as usable as R in statistical
domain. MATLAB is not a fit for doing statistics and R is not a fit for doing linear algebra,
but Julia is perfect for doing both statistics and linear algebra. On the other hand, if we
compare Julia’s type system with R, the former has much richer type system.
12
2. Julia Programming — Environment Setup Julia Programming
To install Julia, we need to download binary Julia platform in executable form which you
can download from the link https://julialang.org/downloads/. On the webpage, you will
find Julia in 32-bit and 64-bit format for all three major platforms, i.e. Linux, Windows,
and Macintosh (OS X). The current stable release which we are going to use is v1.5.1.
Installing Julia
Let us see how we can install Julia on various platforms:
wget https://julialang-s3.julialang.org/bin/linux/x64/1.5/julia-1.5.1-linux-
x86_64.tar.gz
tar zxvf julia-1.5.1-linux-x86_64.tar.gz
Use Julia’s full path, <Julia directory>/bin/Julia to invoke Julia executable. Here
<Julia directory> refers to the directory where Julia is installed on your computer.
You can also create a symbolic link to Julia programming language. The link should
be inside a folder which is on your system PATH.
You can add Julia’s bin folder with full path to system PATH environment variable
by editing the ~/.bashrc or ~/.bash_profile file. It can be done by opening the
file in any of the editors and adding the line given below:
Windows installation
Once you downloaded the installer as per your windows specifications, run the installer. It
is recommended to note down the installation directory which looks like
C:\Users\Ga\AppData\Local\Programs\Julia1.5.1.
To invoke Julia programming language by simply typing Julia in cmd, we must add Julia
executable directory to system PATH. You need to follow the following steps according to
your windows specifications:
On Windows 10
First open Run by using the shortcut Windows key + R.
Now, type rundll32 sysdm.cpl, EditEnvironmentVariables and press enter.
13
Julia Programming
We will now find the row with “Path” under “User Variable” or “System Variable”.
Now click on edit button to get the “Edit environment variable” UI.
Now, click on “New” and paste in the directory address we have noted while
installation (C:\Users\Ga\AppData\Local\Programs\Julia1.5.1\bin).
Finally click OK and Julia is ready to be run from command line by typing Julia.
On Windows 7 or 8
First open Run by using the shortcut Windows key + R.
Now, type rundll32 sysdm.cpl, EditEnvironmentVariables and press enter.
We will now find the row with “Path” under “User Variable” or “System Variable”.
Click on edit button and we will get the “Edit environment variable” UI.
Now move the cursor to the end of this field and check if there is semicolon at the
end or not. If not found, then add a semicolon.
Once added, we need to paste in the directory address we have noted while
installation (C:\Users\Ga\AppData\Local\Programs\Julia1.5.1\bin).
Finally click OK and Julia is ready to be run from command line by typing Julia.
macOS installation
On macOS, a file named Julia-<version>.dmg will be given. This file contains Julia-
<version>.app and you need to drag this file to Applications Folder Shortcut. One other
way to run Julia is from the disk image by opening the app.
If you want to run Julia from terminal, type the below given command:
ln -s /Applications/Julia-1.5.app/Contents/Resources/julia/bin/julia
/usr/local/bin/julia
This command will create a symlink to the Julia version we have chosen. Now close the
shell profile page and quit terminal as well. Now once again open the Terminal and type
julia in it and you will be with your version of Julia programming language.
14
Julia Programming
The above command will download the source code into a julia directory and that is in
current folder.
Now, by using the command given below, install GNU compilation tools g++, gfortran, and
m4:
cd Julia
make
After this, successful build Julia programming language will start up with the ./julia
command.
After clicking on Julia logo, we will get a prompt with julia> for writing our piece of code
or program. Use exit() or CTRL + D to end the session. If you want to evaluate the
expression, press enter after input.
15
Julia Programming
Packages
Almost all the standard libraries in Julia are written in Julia itself but the rest of the Julia’s
code ecosystem can be found in Packages which are Git repositories. Some important
points about Julia packages are given below:
Packages provide reusable functionality that can be easily used by other Julia
projects.
Julia has built-in package manager named pkg.jl for package installation.
The package manager handles installation, removal, and updates of packages.
The package manager works only if the packages are in REPL.
Installing packages
Step 1: First open the Julia command line.
16
Julia Programming
Step 2: Now open the Julia package management environment by pressing, ]. You will
get the following console:
Adding a package
17
Julia Programming
For adding a package in Julia environment, we need to use add command with the name
of the package. For example, we will be adding the package named Graphs which is uses
for working with graphs in Julia.
Removing a package
For removing a package from Julia, we need to use rm command with the name of the of
the package. For example, we will be removing the package named Graphs as follows:
Updating a package
18
Julia Programming
To update a Julia package, either you can use update command, which will update all the
Julia packages, or you can use up command along with the name of the package, which
will update specific package.
Testing a package
Use test command to test a Julia package. For example, below we have tested JSON
package:
19
Julia Programming
Installing IJulia
To install IJulia, use add IJulia command in Julia package environment. We need to make
sure that you have preinstalled Anaconda on your machine. Once it gets installed, open
Jupyter notebook and choose Julia1.5.1 as follows:
Now you will be able to write Julia programs using IJulia as follows:
20
Julia Programming
Installing Juno
Juno is a powerful IDE for Julia programming language. It is free, and to install follow the
steps given below:
Step 2: Now you need to install Atom from here. It must be updated(version 1.41+).
Step 3: In Atom, go to settings and then install panel. It will install Juno for you.
Step 4: Start working in Juno by opening REPL with Juno > open REPL command.
21
3. Julia Programming — Basic Syntax Julia Programming
The simplest first Julia program (and of many other programming languages too) is to
print hello world. The script is as follows:
If you have added Julia to your path, the same script can be saved in a file say hello.jl
and can be run by typing Julia hello.jl at command prompt. Alternatively the same can
also be run from Julia REPL by typing include(“hello.jl”). This command will evaluate all
valid expressions and return the last output.
Variables
What can be the simplest definition of a computer program? The simplest one may be that
a computer program is a series of instructions to be executed on a variety of data.
Here the data can be the name of a person, place, the house number of a person, or even
a list of things you have made. In computer programming, when we need to label such
information, we give it a name (say A) and call it a variable. In this sense, we can say
that a variable is a box containing data.
Let us see how we can assign data to a variable. It is quite simple, just type it. For example,
student_name = “Ram”
roll_no = 15
marks_math = 9.5
Here, the first variable i.e. student_name contains a string, the second variable i.e.
roll_no contains a number, and the third variable i.e. marks_math contains a floating-
point number. We see, unlike other programming languages such as C++, Python, etc.,
22
Julia Programming
in Julia we do not have to specify the type of variables because it can infer the type of
object on the right side of the equal sign.
The names of the variables in Julia are case sensitive. So, the variables
student_name and Student_name would not be same.
The names of the variables in Julia should always start with a letter and after that
we can use anything like digits, letters, underscores, etc.
In Julia, generally lower-case letter is used with multiple words separated by an
underscore.
We should use clear, short, and to the point names for variables.
Some of the valid Julia variable names are student_name, roll_no, speed,
current_time.
Comments
Writing comments in Julia is quite same as Python. Based on the usage, comments are of
two types:
Example
Multi-line Comments
In Julia, the multi-line comment is a piece of text, like single line comment, but it is
enclosed in a delimiter #= on the start of the comment and enclosed in a delimiter =# on
the end of the comment. Given below is the code snippet showing multi-line comment:
Example
23
4. Julia — Arrays Julia Programming
An Array is an ordered set of elements which are often specified with squared brackets
having comma-separated items. We can create arrays that are:
Full or empty
Hold values of different types
Restricted to values of a specific type
In Julia, arrays are actually mutable type collections which are used for lists, vectors,
tables, and matrices. That is why the values of arrays in Julia can be modified with the use
of certain pre-defined keywords. With the help of push! command you can add new
element in array. Similarly, with the help of splice! function you can add elements in an
array at a specified index.
The above example shows that we have created a 1D array with 3 elements each of which
is a 64-bit integer. This 1D array is bound to the variable arr.
Uninitialized array
We can also specify the type and the dimension of an array by using the below syntax:
Array{type}(dims)
24
Julia Programming
3×3×3 Array{Int64,3}:
[:, :, 1] =
8 372354944 328904752
3 331059280 162819664
32 339708912 1
[:, :, 2] =
331213072 3 331355760
1 328841776 331355984
-1 328841680 2
[:, :, 3] =
1 0 339709232
164231472 328841872 347296224
328841968 339709152 16842753
Here we placed the type in curly braces and the dimensions in parentheses. We use undef
which means that particular array has not been initialized to any known value and thats
why we got random numbers in the output.
Arrays of anything
Julia gives us the freedom to create arrays with elements of different types. Let us see the
example below in which we are going to create array of an odd mixture — numbers,
strings, functions, constants:
Empty Arrays
Just like creating an array of specific type, we can also create empty arrays in Julia. The
example is given below:
julia> A = Int64[]
Int64[]
25
Julia Programming
julia> A = String[]
String[]
julia> [1 2 3 4 5 6 7 8 9 10]
1×10 Array{Int64,2}:
1 2 3 4 5 6 7 8 9 10
To add another row, just add a semicolon(;). Let us check the below example:
julia> [1 2 3 4 5 ; 6 7 8 9 10]
2×5 Array{Int64,2}:
1 2 3 4 5
6 7 8 9 10
Collect() function
First useful function to create an array using range objects is collect(). With the help of
colon(:) and collect() function, we can create an array using range objects as follows:
julia> collect(1:5)
5-element Array{Int64,1}:
1
2
3
4
5
julia> collect(1.5:5.5)
5-element Array{Float64,1}:
1.5
26
Julia Programming
2.5
3.5
4.5
5.5
Let us see a three-piece version of a range object with the help of which you can specify
a step size other than 1.
start:step:stop.
julia> collect(0:5:50)
11-element Array{Int64,1}:
0
5
10
15
20
25
30
35
40
45
50
julia> [0:10...]
11-element Array{Int64,1}:
0
1
2
3
4
5
6
27
Julia Programming
7
8
9
10
range() function
Range() is another useful function to create an array with range objects. It goes from
start value to end value by taking a specific step value.
Or you can use range to take 10 steps from 1, stopping at or before 150:
julia> range(1, stop=150, step=10)
1:10:141
28
Julia Programming
29
Julia Programming
16
25
Generator expressions do not build an array to first hold the values rather they generate
the values when needed. Hence they are more useful than comprehensions.
Populating an Array
Following are the functions with the help of which you can create and fill arrays with
specific contents:
zeros (m, n)
This function will create matrix of zeros with m number of rows and n number of columns.
The example is given below:
julia> zeros(4,5)
4×5 Array{Float64,2}:
0.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0
julia> zeros(Int64,4,5)
4×5 Array{Int64,2}:
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0
ones (m, n)
This function will create matrix of ones with m number of rows and n number of columns.
The example is given below:
julia> ones(4,5)
4×5 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 1.0 1.0 1.0 1.0
30
Julia Programming
rand (m, n)
As the name suggests, this function will create matrix of random numbers with m
number of rows and n number of columns. The example is given below:
julia> rand(4,5)
4×5 Array{Float64,2}:
0.514061 0.888862 0.197132 0.721092 0.899983
0.503034 0.81519 0.061025 0.279143 0.204272
0.687983 0.883176 0.653474 0.659005 0.970319
0.20116 0.349378 0.470409 0.000273225 0.83694
randn(m, n)
As the name suggests, this function will create m*n matrix of normally distributed
random numbers with mean=0 and standard deviation(SD)=1.
julia> randn(4,5)
4×5 Array{Float64,2}:
-0.190909 -1.18673 2.17422 0.811674 1.32414
0.837096 -0.0326669 -2.03179 0.100863 0.409234
-1.24511 -0.917098 -0.995239 0.820814 1.60817
-1.00931 -0.804208 0.343079 0.0771786 0.361685
fill()
This function is used to fill an array with a specific value. More specifically, it will create
an array of repeating duplicate value.
julia> fill(100,5)
5-element Array{Int64,1}:
100
100
100
100
100
julia> fill("tutorialspoint.com",3,3)
3×3 Array{String,2}:
"tutorialspoint.com" "tutorialspoint.com" "tutorialspoint.com"
"tutorialspoint.com" "tutorialspoint.com" "tutorialspoint.com"
"tutorialspoint.com" "tutorialspoint.com" "tutorialspoint.com"
31
Julia Programming
fill!()
It is similar to fill() function but the sign of exclamation (!) is an indication or warning that
the content of an existing array is going to be changed. The example is given below:
julia> fill!(ABC,100)
5-element Array{Float64,1}:
100.0
100.0
100.0
100.0
100.0
julia> ABC
5-element Array{Float64,1}:
100.0
100.0
100.0
100.0
100.0
Array Constructor
The function Array(), we have studied earlier, can build array of a specific type as follows:
julia> Array{Int64}(undef, 5)
5-element Array{Int64,1}:
4294967297
8589934593
8589934594
8589934594
32
Julia Programming
As we can see from the output that this array is uninitialized. The odd-looking numbers
are memories’ old content.
Arrays of arrays
Following example demonstrates creating arrays of arrays:
julia> Array[1:5,6:10]
2-element Array{Array,1}:
[1, 2, 3, 4, 5]
[6, 7, 8, 9, 10]
Copying arrays
Suppose you have an array and want to create another array with similar dimensions,
then you can use similar() function as follows:
julia> A = collect(1:5);
julia> B = similar(A)
5-element Array{Int64,1}:
164998448
234899984
383606096
164557488
396984416
Matrix Operations
As we know that a two-dimensional (2D) array can be used as a matrix so all the functions
that are available for working on arrays can also be used as matrices. The condition is that
33
Julia Programming
the dimensions and contents should permit. If you want to type a matrix, use spaces to
make rows and semicolon(;) to separate the rows as follows:
julia> [2 3 ; 4 5]
2×2 Array{Int64,2}:
2 3
4 5
Following is an example to create an array of arrays (as we did earlier) by placing two
arrays next to each other:
julia> Array[[3,4],[5,6]]
2-element Array{Array,1}:
[3, 4]
[5, 6]
Below we can see what happens when we omit the comma and place columns next to each
other:
34
Julia Programming
julia> arr[4]
20
julia> arr[end]
50
julia> arr[end-1]
45
To access more than one element at a time, we can also provide a bunch of index numbers
as shown below:
julia> arr[[2,5,6]]
3-element Array{Int64,1}:
10
25
30
julia> arr[[true, false, true, true,true, false, false, true, true, false]]
6-element Array{Int64,1}:
5
15
20
25
40
45
35
Julia Programming
julia> arr2[1]
10
julia> arr2[2]
13
julia> arr2[1,2]
11
Similarly, for row1 and column3 element, we have to use the below command:
julia> arr2[1,3]
12
We can also use getindex() function to obtain elements from a 2-D array:
julia> getindex(arr2,1,2)
11
julia> getindex(arr2,2,3)
15
Adding Elements
We can add elements to an array in Julia at the end, at the front and at the given index
using push!(), pushfirst!() and splice!() functions respectively.
At the end
We can use push!() function to add an element at the end of an array. For example,
julia> push!(arr,55)
11-element Array{Int64,1}:
5
10
15
20
25
30
35
36
Julia Programming
40
45
50
55
Remember we had 10 elements in array arr. Now push!() function added the element 55
at the end of this array.
The exclamation(!) sign represents that the function is going to change the array.
At the front
We can use pushfirst!() function to add an element at the front of an array. For example,
julia> pushfirst!(arr,0)
12-element Array{Int64,1}:
0
5
10
15
20
25
30
35
40
45
50
55
At a given index
We can use splice!() function to add an element into an array at a given index. For
example,
julia> splice!(arr,2:5,2:6)
4-element Array{Int64,1}:
5
10
15
20
julia> arr
37
Julia Programming
13-element Array{Int64,1}:
0
2
3
4
5
6
25
30
35
40
45
50
55
Removing Elements
We can remove elements at last position, first position and at the given index, from an
array in Julia, using pop!(), popfirst!() and splice!() functions respectively.
julia> pop!(arr)
55
julia> arr
12-element Array{Int64,1}:
0
2
3
4
5
6
25
30
35
40
38
Julia Programming
45
50
julia> popfirst!(arr)
0
julia> arr
11-element Array{Int64,1}:
2
3
4
5
6
25
30
35
40
45
50
julia> splice!(arr,5)
6
julia> arr
10-element Array{Int64,1}:
2
3
4
5
25
30
39
Julia Programming
35
40
45
50
40
5. Julia — Tuples Julia Programming
Similar to an array, tuple is also an ordered set of elements. Tuples work in almost the
same way as arrays but there are following important differences between them:
Creating tuples
We can create tuples as arrays and most of the array’s functions can be used on tuples
also. Some of the example are given below:
julia> tupl=(5,10,15,20,25,30)
(5, 10, 15, 20, 25, 30)
julia> tupl
(5, 10, 15, 20, 25, 30)
julia> tupl[3:end]
(15, 20, 25, 30)
julia> tupl[1]
(1, 2)
julia> tupl[1][2]
2
We cannot change a tuple:
julia> tupl[2]=0
ERROR: MethodError: no method matching
setindex!(::Tuple{Tuple{Int64,Int64},Tuple{Int64,Int64}}, ::Int64, ::Int64)
Stacktrace:
[1] top-level scope at REPL[7]:1
41
Julia Programming
Named tuples
A named tuple is simply a combination of a tuple and a dictionary because:
Example
julia> shape_item2.corner1
(100, 100)
julia> shape_item2.corner2
(200, 200)
Example
42
Julia Programming
julia> shape_item = (corner1 = (1, 1), corner2 = (-1, -1), center = (0, 0))
(corner1 = (1, 1), corner2 = (-1, -1), center = (0, 0))
julia> shape_item.corner1
(1, 1)
julia> shape_item.corner2
(-1, -1)
julia> shape_item.center
(0, 0)
julia> (shape_item.center,shape_item.corner2)
((0, 0), (-1, -1))
We can also access all the values as with ordinary tuples as follows:
julia> c1
(1, 1)
Example
julia> shape_item = (corner1 = (1, 1), corner2 = (-1, -1), center = (0, 0))
(corner1 = (1, 1), corner2 = (-1, -1), center = (0, 0))
43
Julia Programming
It is also possible to define a named tuple which contains the names as well values for one
or more keywords as follows:
In order to pass the named tuples to the function we need to use; while calling the
function:
The values and keyword can also be overridden by later function as follows:
44
6. Julia — Integers and Floating-Point Numbers Julia Programming
In any programming language, there are two basic building blocks of arithmetic and
computation. They are integers and floating-point values. Built-in representation of
the values of integers and floating-point are called numeric primitives. On the other
hand, their representation as immediate values in code are called numeric literals.
Integers
Integer is one of the primitive numeric types in Julia. It is represented as follows:
julia> 100
100
julia> 123456789
123456789
We can check the default type of an integer literal, which depends on whether our system
is 32-bit or 64-bit architecture.
julia> Sys.WORD_SIZE
64
julia> typeof(100)
Int64
Integer types
The table given below shows the integer types in Julia:
UInt8 8 0 2^8 – 1
45
Julia Programming
UInt16 16 0 2^16 – 1
UInt32 32 0 2^32 – 1
UInt64 64 0 2^64 – 1
Overflow behavior
In Julia, if the maximum representable value of a given type exceeds, then it results in a
wraparound behavior. For example:
julia> A = typemax(Int64)
9223372036854775807
julia> A + 1
-9223372036854775808
julia> A + 1 == typemin(Int64)
true
julia> 10^19
-8446744073709551616
46
Julia Programming
julia> big(10)^19
10000000000000000000
Division errors
Integer division throws a DivideError in the following two exceptional cases:
Dividing by zero
Dividing the lowest negative number
The rem (remainder) and mod (modulus) functions will throw a DivideError whenever
their second argument is zero. The example are given below:
julia> mod(1, 0)
ERROR: DivideError: integer division error
Stacktrace:
[1] div at .\int.jl:260 [inlined]
[2] div at .\div.jl:217 [inlined]
[3] div at .\div.jl:262 [inlined]
[4] fld at .\div.jl:228 [inlined]
[5] mod(::Int64, ::Int64) at .\int.jl:252
[6] top-level scope at REPL[52]:1
julia> rem(1, 0)
ERROR: DivideError: integer division error
Stacktrace:
[1] rem(::Int64, ::Int64) at .\int.jl:261
[2] top-level scope at REPL[54]:1
Floating-point numbers
Another primitive numeric types in Julia is floating-point numbers. It is represented (using
E-notation when needed) as follows:
julia> 1.0
1.0
julia> 0.5
0.5
47
Julia Programming
julia> -1.256
-1.256
julia> 2e11
2.0e11
julia> 3.6e-5
3.6e-5
All the above results are Float64. If we would like to enter Float32 literal, they can be
written by writing f in the place of e as follows:
julia> 0.5f-5
5.0f-6
julia> typeof(ans)
Float32
julia> 1.5f0
1.5f0
julia> typeof(ans)
Float32
Floating-point types
The table given below shows the floating-point types in Julia:
Float16 half 16
Float32 single 32
Float64 double 64
Floating-point zeros
There are two kind of floating-point zeros, one is positive zero and other is negative zero.
They are same but their binary representation is different. It can be seen in the example
below:
48
Julia Programming
julia> bitstring(0.0)
"0000000000000000000000000000000000000000000000000000000000000000"
julia> bitstring(-0.0)
"1000000000000000000000000000000000000000000000000000000000000000"
Inf16 Inf32 Inf positive It is the value greater than all finite
infinity floating-point values
-Inf16 -Inf32 -Inf negative It is the value less than all finite
infinity floating-point values
julia> (typemin(Float16),typemax(Float16))
(-Inf16, Inf16)
julia> (typemin(Float32),typemax(Float32))
(-Inf32, Inf32)
julia> (typemin(Float64),typemax(Float64))
(-Inf, Inf)
Machine epsilon
Machine epsilon is the distance between two adjacent representable floating-point
numbers. It is important to know machine epsilon because most of the real numbers
cannot be represented exactly with floating-point numbers.
49
Julia Programming
In Julia, we have eps() function that gives us the distance between 1.0 and the next
larger representable floating-point value. The example is given below:
julia> eps(Float32)
1.1920929f-7
julia> eps(Float64)
2.220446049250313e-16
Rounding modes
As we know that the number should be rounded to an appropriate representable value if
it does not have an exact floating-point representation. Julia uses the default mode called
RoundNearest. It rounds to the nearest integer, with ties being rounded to the nearest
even integer. For example,
julia> BigFloat("1.510564889",2,RoundNearest)
1.5
50
7. Julia — Rational and Complex Numbers Julia Programming
Rational Numbers
Julia represents exact ratios of integers with the help of rational number type. Let us
understand about rational numbers in Julia in further sections:
julia> 4//5
4//5
You can also extract the standardized numerator and denominator as follows:
julia> numerator(8//9)
8
julia> denominator(8//9)
9
julia> float(2//3)
0.6666666666666666
Converting rational to floating-point numbers does not loose the following
identity for any integral values of A and B. For example:
51
Julia Programming
Complex Numbers
As we know that the global constant im, which represents the principal square root of -1,
is bound to the complex number. This binding in Julia suffice to provide convenient syntax
for complex numbers because Julia allows numeric literals to be contrasted with identifiers
as coefficients.
julia> 2+3im
2 + 3im
julia> (2 + 3im)^2
-5 + 12im
julia> (2 + 3im)^2.6
-23.375430842463754 + 15.527174176755075im
52
Julia Programming
julia> (2 + 3im)-1
1 + 3im
julia> (2 + 3im)+0.7
2.7 + 3.0im
julia> (2 + 3im)-0.7im
2.0 + 2.3im
julia> (2 + 3im)/2
1.0 + 1.5im
julia> (2 + 3im)/(1-3im)
-0.7000000000000001 + 0.8999999999999999im
julia> 3im^3
0 - 3im
julia> 1+2/5im
1.0 - 0.4im
53
Julia Programming
Let us check out the use of Elementary Functions for complex numbers in the below
example:
54
8. Julia — Basic Operators Julia Programming
Arithmetic Operators
In Julia, we get all the basic arithmetic operators across all the numeric primitive types. It
also provides us bitwise operators as well as efficient implementation of comprehensive
collection of standard mathematical functions.
Following table shows the basic arithmetic operators that are supported on Julia’s primitive
numeric types:
55
Julia Programming
The promotion system of Julia makes these arithmetic operations work naturally and
automatically on the mixture of argument types.
Example
Following example shows the use of arithmetic operators:
julia> 2+20-5
17
julia> 3-8
-5
julia> 50*2/10
10.0
julia> 23%2
1
julia> 2^4
16
Bitwise Operators
Following table shows the bitwise operators that are supported on Julia’s primitive numeric
types:
Expression Name
~x bitwise not
x | y bitwise or
56
Julia Programming
Example
Following example shows the use of bitwise operators:
julia> ~1009
-1010
julia> 12&23
4
julia> 12 & 23
4
julia> 12 | 23
31
julia> 12 ⊻ 23
27
julia> ~UInt32(12)
0xfffffff3
julia> ~UInt8(12)
0xf3
Updating Operators
Each arithmetic as well as bitwise operator has an updating version which can be formed
by placing an equal sign (=) immediately after the operator. This updating operator
assigns the result of the operation back into its left operand. It means that a +=1 is equal
to a = a+1.
57
Julia Programming
Following is the list of the updating versions of all the binary arithmetic and bitwise
operators:
+=
-=
*=
/=
\=
÷=
%=
^=
&=
|=
⊻=
>>>=
>>=
<<=
Example
Following example shows the use of updating operators:
julia> A = 100
100
julia> A +=100
200
julia> A
200
Example
Following example shows the use of “dot” operator:
58
Julia Programming
Operator Name
== Equality
!=, ≠ inequality
Example
Following example shows the use of numeric comparison operators:
59
Julia Programming
Chaining Comparisons
In Julia, the comparisons can be arbitrarily chained. In case of numerical code, the chaining
comparisons are quite convenient. The && operator for scalar comparisons and & operator
for elementwise comparison allows chained comparisons to work fine on arrays.
Example
Following example shows the use of chained comparison:
julia> 100 < 200 <= 200 < 300 == 300 > 200 >= 100 == 100 < 300 != 500
true
In the following example, let us check out the evaluation behavior of chained comparisons:
60
Julia Programming
Exponentiation ^ Right
Unary + - √ Right
Fractions // Left
Addition + - | ⊻ Left
Syntax : .. Left
Non-
Comparisons > < >= <= == === != !== <:
associative
61
Julia Programming
= += -= *= /= //= \= ^= ÷= %= |= &= ⊻=
Assignments Right
<<= >>= >>>=
62
9. Julia — Basic Mathematical Functions Julia Programming
Let us try to understand basic mathematical functions with the help of example in this
chapter.
Numerical Conversions
In Julia, the user gets three different forms of numerical conversion. All the three differ in
their handling of inexact conversions. They are as follows:
T(x) or convert(T, x): This notation converts x to a value of T. The result depends upon
following two cases:
T is an integer type: The result will raise an InexactError if and only if x is not
representable by T.
x%T: This notation will convert an integer x to a value of integer type T corresponding to
x modulo 2^n. Here n represents the number of bits in T. In simple words, this notation
truncates the binary representation to fit.
Rounding functions: This notation takes a type T as an optional argument for calculation.
Eg: Round(Int, a) is shorthand for Int(round(a)).
Example
The example given below represent the various forms described above:
julia> Int8(110)
110
julia> Int8(128)
ERROR: InexactError: trunc(Int8, 128)
Stacktrace:
[1] throw_inexacterror(::Symbol, ::Type{Int8}, ::Int64) at .\boot.jl:558
[2] checked_trunc_sint at .\boot.jl:580 [inlined]
[3] toInt8 at .\boot.jl:595 [inlined]
[4] Int8(::Int64) at .\boot.jl:705
[5] top-level scope at REPL[4]:1
julia> Int8(110.0)
110
63
Julia Programming
julia> Int8(3.14)
ERROR: InexactError: Int8(3.14)
Stacktrace:
[1] Int8(::Float64) at .\float.jl:689
[2] top-level scope at REPL[6]:1
julia> Int8(128.0)
ERROR: InexactError: Int8(128.0)
Stacktrace:
[1] Int8(::Float64) at .\float.jl:689
[2] top-level scope at REPL[7]:1
julia> 110%Int8
110
julia> 128%Int8
-128
Rounding functions
Following table shows rounding functions that are supported on Julia’s primitive numeric
types:
64
Julia Programming
floor(x) This function will round x towards -Inf returns the typeof(x)
nearest integral value of the same type as x. This
value will be less than or equal to x.
Example
The example given below represent the rounding functions:
julia> round(3.8)
4.0
julia> round(Int, 3.8)
4
julia> floor(3.8)
3.0
julia> floor(Int, 3.8)
65
Julia Programming
3
julia> ceil(3.8)
4.0
julia> ceil(Int, 3.8)
4
julia> trunc(3.8)
3.0
julia> trunc(Int, 3.8)
3
Division functions
Following table shows the division functions that are supported on Julia’s primitive numeric
types:
Function Description
div(x,y), x÷y It is the quotation from Euclidean division. Also called truncated
division. It computes x/y and the quotient will be rounded towards
zero.
fld(x,y) It is the floored division. The quotient will be rounded towards -Inf
i.e. largest integer less than or equal to x/y. It is shorthand for div(x,
y, RoundDown).
cld(x,y) It is ceiling division. The quotient will be rounded towards +Inf i.e.
smallest integer less than or equal to x/y. It is shorthand for div(x, y,
RoundUp).
mod2pi(x) It is modulus with respect to 2pi. It satisfies 0 <= mod2pi(x) < 2pi
66
Julia Programming
Example
The example given below represent the division functions:
julia> div(11, 4)
2
julia> div(7, 4)
1
julia> fld(11, 4)
2
julia> fld(-5,3)
-2
julia> fld(7.5,3.3)
2.0
julia> cld(7.5,3.3)
3.0
julia> mod(8.9,2)
0.9000000000000004
67
Julia Programming
julia> rem(8,4)
0
julia> rem(9,4)
1
julia> mod2pi(7*pi/5)
4.39822971502571
julia> divrem(8,3)
(2, 2)
julia> fldmod(12,4)
(3, 0)
julia> fldmod(13,4)
(3, 1)
julia> mod1(5,4)
1
julia> gcd(6,0)
6
julia> gcd(1//3,2//3)
1//3
julia> lcm(1//3,2//3)
2//3
68
Julia Programming
Function Description
sign(x) This function indicates the sign of x. It will return -1, 0, or +1.
This function indicates whether the sign bit is on (true) or off (false).
signbit(x) In simple words, it will return true if the value of the sign of x is -ve,
otherwise it will return false.
It returns a value Z which has the magnitude of x and the same sign
copysign(x,y)
as y.
It returns a value with the magnitude of x and the sign of x*y. The
flipsign(x,y)
sign will be flipped if y is negative. Example: abs(x) = flipsign(x,x).
Example
The example given below represent the sign and absolute value functions:
julia> abs(-7)
7
julia> abs(5+3im)
5.830951894845301
julia> abs2(-7)
49
julia> abs2(5+3im)
34
julia> copysign(5,-10)
-5
julia> copysign(-5,10)
69
Julia Programming
julia> sign(5)
1
julia> sign(-5)
-1
julia> signbit(-5)
true
julia> signbit(5)
false
julia> flipsign(5,10)
5
julia> flipsign(5,-10)
-5
Function Description
It will return the square root of x. For negative real arguments, it will
sqrt(x), √x
throw DomainError.
cbrt(x), ∛x It will return the cube root of x. It also accepts the negative values.
70
Julia Programming
It will accurately compute the log(1+x) for x near zero. For negative
log1p(x)
real arguments, it will throw DomainError.
Example
The example given below represent the Power, Logs, and Roots functions:
julia> sqrt(49)
7.0
julia> sqrt(-49)
ERROR: DomainError with -49.0:
sqrt will only return a complex result if called with a complex argument. Try
sqrt(Complex(x)).
Stacktrace:
[1] throw_complex_domainerror(::Symbol, ::Float64) at .\math.jl:33
[2] sqrt at .\math.jl:573 [inlined]
[3] sqrt(::Int64) at .\math.jl:599
[4] top-level scope at REPL[43]:1
julia> cbrt(8)
71
Julia Programming
2.0
julia> cbrt(-8)
-2.0
julia> a = Int64(5)^10;
julia> hypot(a, a)
1.3810679320049757e7
julia> exp(5.0)
148.4131591025766
julia> expm1(10)
22025.465794806718
julia> expm1(1.0)
1.718281828459045
julia> ldexp(4.0, 2)
16.0
julia> log(5,2)
0.43067655807339306
julia> log(4,2)
0.5
julia> log(4)
1.3862943611198906
julia> log2(4)
2.0
julia> log10(4)
0.6020599913279624
72
Julia Programming
julia> log1p(4)
1.6094379124341003
julia> log1p(-2)
ERROR: DomainError with -2.0:
log1p will only return a complex result if called with a complex argument. Try
log1p(Complex(x)).
Stacktrace:
[1] throw_complex_domainerror(::Symbol, ::Float64) at .\math.jl:33
[2] log1p(::Float64) at .\special\log.jl:356
[3] log1p(::Int64) at .\special\log.jl:395
[4] top-level scope at REPL[65]:1
julia> exponent(6.8)
2
julia> significand(15.2)/10.2
0.18627450980392157
julia> significand(15.2)*8
15.2
Julia also provides two additional functions namely sinpi(x) and cospi(x) for accurately
computing sin(pi*x) and cos(pi*x).
If you want to compute the trigonometric functions with degrees, then suffix the functions
with d as follows:
73
Julia Programming
julia> cos(56)
0.853220107722584
julia> cosd(56)
0.5591929034707468
74
10. Julia — Strings Julia Programming
A string may be defined as a finite sequence of one or more characters. They are usually
enclosed in double quotes. For example: “This is Julia programming language”.
Following are important points about strings:
Strings are immutable, i.e., we cannot change them once they are created.
It needs utmost care while using two specific characters: double quotes(“), and
dollar sign($). It is because if we want to include a double quote character in the
string then it must precede with a backslash; otherwise we will get different results
because then the rest of the string would be interpreted as Julia code. On the other
hand, if we want to include a dollar sign then it must also precede with a backslash
because dollar sign is used in string interpolation.
In Julia, the built-in concrete type used for strings as well as string literals is String
which supports full range of Unicode characters via the UTF-8 encoding.
All the string types in Julia are subtypes of the abstract type AbstractString. If
you want Julia to accept any string type, you need to declare the type as
AbstractString.
Characters
A single character is represented with Char value. Char is a 32-bit primitive type which
can be converted to a numeric value (which represents Unicode code point).
julia> 'a'
'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)
julia> typeof(ans)
Char
julia> Int('a')
97
julia> typeof(ans)
Int64
75
Julia Programming
julia> Char(97)
'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)
With Char values, we can do some arithmetic as well as comparisons. This can be
understood with the help of following example:
julia> 'x' + 1
'y': ASCII/Unicode U+0079 (category Ll: Letter, lowercase)
76
Julia Programming
Just like a normal value, we can perform arithmetic as well as other operations with end.
Check the below given example:
julia> str[end-1]
'.': ASCII/Unicode U+002E (category Po: Punctuation, other)
julia> str[end÷2]
'g': ASCII/Unicode U+0067 (category Ll: Letter, lowercase)
julia> str[6:9]
"is J"
Using SubString
In the above method, the Range indexing makes a copy of selected part of the original
string, but we can use SubString to create a view into a string as given in the below
example:
julia> typeof(substr)
SubString{String}
Another encoding is UTF-8, a variable-width encoding, that is used to encode string literals.
Here the variable-width encoding means that all the characters are not encoded in the
same number of bytes, i.e., code units. For example, in UTF-8:
ASCII characters (with code points less than 080(128) are encoded, using a single
byte, as they are in ASCII.
On the other hand, the code points 080(128) and above are encoded using
multiple bytes (up to four per character).
77
Julia Programming
The code units (bytes for UTF-8), which we have mentioned above, are String indices in
Julia. They are actually the fixed-width building blocks that are used to encode arbitrary
characters. In other words, every index into a String is not necessarily a valid index. You
can check out the example below:
julia> s[1]
'∀': Unicode U+2200 (category Sm: Symbol, math)
julia> s[2]
ERROR: StringIndexError("∀ x ∃ y", 2)
Stacktrace:
[1] string_index_err(::String, ::Int64) at .\strings\string.jl:12
[2] getindex_continued(::String, ::Int64, ::UInt32) at .\strings\string.jl:220
[3] getindex(::String, ::Int64) at .\strings\string.jl:213
String Concatenation
Concatenation is one of the most useful string operations. Following is an example of
concatenation:
julia> A = "Hello"
"Hello"
julia> B = "Julia Programming Language"
"Julia Programming Language"
julia> string(A, ", ", B, ".\n")
"Hello, Julia Programming Language.\n"
We can also concatenate strings in Julia with the help of *. Given below is the example for
the same:
julia> A = "Hello"
"Hello"
julia> B = "Julia Programming Language"
"Julia Programming Language"
julia> A * ", " * B * ".\n"
"Hello, Julia Programming Language.\n"
78
Julia Programming
Interpolation
It is bit cumbersome to concatenate strings using concatenation. Therefore, Julia allows
interpolation into strings and reduce the need for these verbose calls to strings. This
interpolation can be done by using dollar sign ($). For example:
julia> A = "Hello"
"Hello"
julia> B = "Julia Programming Language"
"Julia Programming Language"
julia> "$A, $B.\n"
"Hello, Julia Programming Language.\n"
Julia takes the expression after $ as the expression whose whole value is to be interpolated
into the string. That’s the reason we can interpolate any expression into a string using
parentheses. For example:
Now if you want to use a literal $ in a string then you need to escape it with a backslash
as follows:
Triple-quoted strings
We know that we can create strings with triple-quotes as given in the below example:
Triple-quoted strings are dedented to the level of the least-intended line, hence this
becomes very useful for defining code that is indented. Following is an example of the
same:
The longest common starting sequence of spaces or tabs in all lines is known as the
dedentation level but it excludes the following:
79
Julia Programming
That is why for all the lines the common starting sequence will be removed by Julia. You
can check out the example below:
Search operators
Julia provides us findfirst and findlast functions to search for the index of a particular
character in string. You can check the below example of both these functions:
80
Julia Programming
Julia also provides us findnext and findprev functions to start the search for a character
at a given offset. Check the below example of both these functions:
It is also possible to check if a substring is found within a string or not. We can use
occursin function for this. The example is given below:
Raw String literals are another useful non-standard string literal. They, without
interpolation or unescaping can be expressed in the form of raw”…”. They create ordinary
String objects containing enclosed contents same as entered without interpolation or
unescaping.
Example
Example
julia> b"DATA\xff\u2200"
8-element Base.CodeUnits{UInt8,String}:
0x44
0x41
0x54
0x41
0xff
0xe2
0x88
0x80
The above resulting byte array is not a valid UTF-8 string as you can see below:
julia> isvalid("DATA\xff\u2200")
false
Example
82
Julia Programming
We can define the version specific behavior by using the following statement:
Regular Expressions
Julia has Perl-compatible Regular Expressions, which are related to strings in the following
ways:
Example
julia> r"^\s*(?:#|$)"
r"^\s*(?:#|$)"
julia> typeof(ans)
Regex
83
11. Julia — Functions Julia Programming
Function, the building blocks of Julia, is a collected group of instructions that maps a tuple
of argument values to a return value. It acts as the subroutines, procedures, blocks, and
other similar structures concepts found in other programming languages.
Defining Functions
There are following three ways in which we can define functions:
When there is a single expression in a function, you can define it by writing the name
of the function and any arguments in parentheses on the left side and write an expression
on the right side of an equal sign.
Example
julia> f(a) = a * a
f (generic function with 1 method)
julia> f(5)
25
julia> func(5, 4)
6.4031242374328485
If there are multiple expressions in a function, you can define it as shown below:
function functionname(args)
expression
expression
expression
...
expression
end
Example
julia> function bills(money)
84
Julia Programming
if money < 0
return false
else
return true
end
end
bills (generic function with 1 method)
julia> bills(50)
true
julia> bills(-50)
false
Example
julia> function mul(x,y)
x+y, x*y
end
mul (generic function with 1 method)
Optional Arguments
It is often possible to define functions with optional arguments i.e. default sensible values
for functions arguments so that the function can use that value if specific values are not
provided. For example:
85
Julia Programming
You can check in the above output that when we call this function without supplying third
value, the variable cz defaults to 0.
Keyword Arguments
Some functions which we define need a large number of arguments but calling such
functions can be difficult because we may forget the order in which we have to supply the
arguments. For example, check the below function:
function foo(a, b, c, d, e, f)
...
end
Now, we may forget the order of arguments and the following may happen:
Julia provides us a way to avoid this problem. We can use keywords to label arguments.
We need to use a semicolon after the function’s unlabelled arguments and follow it with
one or more keyword-value pair as follows:
julia> foo(100,20)
a is 100
b is 20
"c => 10, d => hi"
86
Julia Programming
It is not necessary to define the keyword argument at the end or in the matching place, it
can be written anywhere in the argument list. Following is an example:
Anonymous Functions
It is waste of time thinking a cool name for your function. Use Anonymous functions i.e.
functions with no name instead. In Julia, such functions can be used in number of places
such as map() and in list comprehensions.
The syntax of anonymous functions uses the symbol ->. You can check the below example:
A -> A^3 + 3A - 3
The above function is an anonymous function that takes an argument A and returns A^3
+ 3A – 3.
It can be used with map() function whose first argument is a function and we can define
an one-off function that exists just for one particular map() operation. The example is
given below:
Once the map() function finishes, the function and argument both will disappear:
julia> A
ERROR: UndefVarError: A not defined
Recursive Functions
In Julia, the functions can be nested. It is demonstrated in the example given below:
end
add (generic function with 1 method)
julia> d = 10
10
julia> add(d)
21
In the same way, a function in Julia can be recursive also. It means the function can call
itself. Before getting into details, we first need to test a condition in code which can be
done with the help of ternary operator “?”. It takes the form expr ? a : b. It is called
ternary because it takes three arguments. Here the expr is a condition, if it is true then a
will be evaluated otherwise b. Let us use this in the following recursive definition:
The above statement calculates the sum of all the integers up to and including a certain
number. But in this recursion ends because there is a base case, i.e., when x is 1, this
value is returned.
The most famous example of recursion is to calculate the nth Fibonacci number which
is defined as the sum of two previous Fibonacci numbers. Let us understand it with the
below given example:
Therefore while using recursion, we need to be careful to define a base case to stop
calculation.
Map
Map may be defined as a function that takes the following form:
map(func, coll)
Here, func is a function applied successively to each element of collection coll. Map
generally contains the anonymous function and returns a new collection. The example is
given below:
88
Julia Programming
-17
Filter
Filter may be defined as a function that takes the following form:
filter(function, collection)
Filter function returns a copy of collection and removes elements for which the function
is false. The example is given below:
Generic Functions
In Julia, we saw that all the functions are inherently defined as Generic. It means that
the functions can be used for different types of their arguments. In simple words,
whenever the function will be called with arguments of a new type, the Julia compiler will
generate a separate version of that function.
On the other hand, a function for a specific combination of arguments types is called a
Method. So, in order to define a new method for a function, which is called overloading,
we need to use the same function name but with different arguments types.
Multiple dispatch
Julia has a mechanism called Multiple Dispatch, which neither Python nor C++ implements.
Under this mechanism, Julia will do a lookup in the vtable at runtime (whenever a function
is called) to find which existing method it should call based on the types of all its
arguments.
Let us understand the concept of multiple dispatch with the help of an example in which
we will define a function that takes 2 arguments returning a string. But in some methods
we will annotate the types of both arguments or single argument.
89
Julia Programming
We have seen that this returns foo with 5 methods. When A and B have no types(as in
base case), then their type is any.
From the following, we can see how the appropriate method will be chosen:
The advantage of multiple dispatch is that it will never result in error because if no other
method is matched, the base case method will be invoked, for sure.
90
12. Julia — Flow Control Julia Programming
As we know that each line of a program in Julia is evaluated in turn hence it provides many
of the control statements (familiar to other programming languages) to control and modify
the flow of evaluation.
Following are different ways to control the flow in Julia programming language:
Ternary expressions
It takes the form expr ? a : b. It is called ternary because it takes three arguments. The
expr is a condition and if it is true then a will be evaluated otherwise b. Example for this
is given below:
julia> A = 100
100
91
Julia Programming
Example
└ @ Main REPL[5]:1
Example
Example
julia> fruit = "Apple"
"Apple"
92
Julia Programming
I like Apple
I like Banana.
But I prefer Apple.
for loops
Some of the common example of iteration are:
We can iterate through various types of objects like arrays, sets, dictionaries, and strings
by using “for” loop (for…end construction). Let us understand the syntax with the
following example:
93
Julia Programming
35
40
45
50
In the above code, the variable ‘i’ takes the value of each element in the array and hence
will step from 0 to 50 in steps of 5.
julia> c = [1]
julia> 1-element Array{Int64,1}:
1
julia> for i in c
push!(c, i)
@show c
sleep(1)
end
c = [1,1]
c = [1,1,1]
c = [1,1,1,1]
...
Loop variables
Loop variable is a variable that steps through each item. It exists only inside the loop. It
disappears as soon as the loop finishes.
Example
julia> for i in 0:5:50
println(i)
end
0
94
Julia Programming
5
10
15
20
25
30
35
40
45
50
julia> i
ERROR: UndefVarError: i not defined
Example
Julia provides global keyword for remembering the value of the loop variable outside the
loop.
julia> hello
9
Example
julia> for x in 1:10
y = x^2
println("$(x) squared is $(y)")
end
95
Julia Programming
Output
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
6 squared is 36
7 squared is 49
8 squared is 64
9 squared is 81
10 squared is 100
julia> y
ERROR: UndefVarError: y not defined
Continue Statement
The Continue statement is used to skip the rest of the code inside the loop and start the
loop again with the next value. It is mostly used in the case when on a particular iteration
you want to skip to the next value.
Example
julia> for x in 1:10
if x % 4 == 0
continue
end
println(x)
end
Output
1
2
3
5
6
7
96
Julia Programming
9
10
Comprehensions
Generating and collecting items something like [n for n in 1:5] is called array
comprehensions. It is sometimes called list comprehensions too.
Example
julia> [X^2 for X in 1:5]
5-element Array{Int64,1}:
1
4
9
16
25
Example
julia> Complex[X^2 for X in 1:5]
5-element Array{Complex,1}:
1 + 0im
4 + 0im
9 + 0im
16 + 0im
25 + 0im
Enumerated arrays
Sometimes we would like to go through an array element by element while keeping track
of the index number of every element of that array. Julia has enumerate() function for this
task. This function gives us an iterable version of something. This function will produce
the index number as well as the value at each index number.
Example
julia> arr = rand(0:9, 4, 4)
4×4 Array{Int64,2}:
7 6 5 8
8 6 9 4
97
Julia Programming
6 3 0 7
2 3 2 4
Zipping arrays
Using the zip() function, you can work through two or more arrays at the same time by
taking the 1st element of each array first and then the 2nd one and so on.
Example
julia> for x in zip(0:10, 100:110, 200:210)
println(x)
end
(0, 100, 200)
(1, 101, 201)
(2, 102, 202)
(3, 103, 203)
(4, 104, 204)
(5, 105, 205)
(6, 106, 206)
(7, 107, 207)
(8, 108, 208)
(9, 109, 209)
(10, 110, 210)
Nested loops
Nest a loop inside another one can be done with the help of using a comma (;) only. You
do not need to duplicate the for and end keywords.
Example
julia> for n in 1:5, m in 1:5
@show (n, m)
end
(n, m) = (1, 1)
(n, m) = (1, 2)
(n, m) = (1, 3)
(n, m) = (1, 4)
99
Julia Programming
(n, m) = (1, 5)
(n, m) = (2, 1)
(n, m) = (2, 2)
(n, m) = (2, 3)
(n, m) = (2, 4)
(n, m) = (2, 5)
(n, m) = (3, 1)
(n, m) = (3, 2)
(n, m) = (3, 3)
(n, m) = (3, 4)
(n, m) = (3, 5)
(n, m) = (4, 1)
(n, m) = (4, 2)
(n, m) = (4, 3)
(n, m) = (4, 4)
(n, m) = (4, 5)
(n, m) = (5, 1)
(n, m) = (5, 2)
(n, m) = (5, 3)
(n, m) = (5, 4)
(n, m) = (5, 5)
While loops
We use while loops to repeat some expressions while a condition is true. The construction
is like while…end.
Example
julia> n = 0
0
3
4
5
6
7
8
9
Exceptions
Exceptions or try…catch construction is used to write the code that checks for the errors
and handles them elegantly. The catch phrase handles the problems that occur in the
code. It allows the program to continue rather than grind to a halt.
Example
julia> str = "string";
julia> try
str[1] = "p"
catch e
println("the code caught an error: $e")
println("but we can easily continue with execution...")
end
the code caught an error: MethodError(setindex!, ("string", "p", 1),
0x0000000000006cba)
but we can easily continue with execution...
Do block
Do block is another syntax form similar to list comprehensions. It starts at the end and
work towards beginning.
Example
julia> Prime_numbers = [1,2,3,5,7,11,13,17,19,23];
101
Julia Programming
As we can see from the above code that the first argument of the find() function. It
operates on the second. But with a do block we can put the function in a do…end block
construction.
julia> findall(Prime_numbers) do x
isequal(x, 19)
end
1-element Array{Int64,1}:
9
102
13. Julia — Dictionaries and Sets Julia Programming
Many of the functions we have seen so far are working on arrays and tuples. Arrays are
just one type of collection, but Julia has other kind of collections too. One such collection
is Dictionary object which associates keys with values. That is why it is called an
‘associative collection’.
To understand it better, we can compare it with simple look-up table in which many types
of data are organized and provide us the single piece of information such as number, string
or symbol called the key. It doesn’t provide us the corresponding data value.
Creating Dictionaries
The syntax for creating a simple dictionary is as follows:
In the above syntax, key1, key2…keyn are the keys and value1, value2,…valuen are the
corresponding values. The operator => is the Pair() function. We can not have two keys
with the same name because keys are always unique in dictionaries.
Example
julia> first_dict = Dict("X" => 100, "Y" => 110, "Z" => 220)
Dict{String,Int64} with 3 entries:
"Y" => 110
"Z" => 220
"X" => 100
We can also create dictionaries with the help of comprehension syntax. The example is
given below:
Example
julia> first_dict = Dict(string(x) => sind(x) for x = 0:5:360)
Dict{String,Float64} with 73 entries:
"320" => -0.642788
"65" => 0.906308
"155" => 0.422618
"335" => -0.422618
"75" => 0.965926
"50" => 0.766044
⋮ => ⋮
103
Julia Programming
Keys
As discussed earlier, dictionaries have unique keys. It means that if we assign a value to
a key that already exists, we will not be creating a new one but modifying the existing
key. Following are some operations on dictionaries regarding keys:
julia> first_dict = Dict("X" => 100, "Y" => 110, "Z" => 220)
Dict{String,Int64} with 3 entries:
"Y" => 110
"Z" => 220
"X" => 100
julia> first_dict
Dict{String,Int64} with 4 entries:
"Y" => 110
104
Julia Programming
Delete a key
We can use delete!() function to delete a key from an existing dictionary:
julia> keys(first_dict)
Base.KeySet for a Dict{String,Int64} with 3 entries. Keys:
"Y"
"Z"
"X"
Values
Every key in dictionary has a corresponding value. Following are some operations on
dictionaries regarding values:
julia> values(first_dict)
Base.ValueIterator for a Dict{String,Int64} with 3 entries. Values:
110
220
100
for kv in first_dict
105
Julia Programming
println(kv)
end
"Y" => 110
"Z" => 220
"X" => 100
Sorting a dictionary
Dictionaries do not store the keys in any particular order hence the output of the dictionary
would not be a sorted array. To obtain items in order, we can sort the dictionary:
Example
julia> first_dict = Dict("R" => 100, "S" => 220, "T" => 350, "U" => 400, "V" =>
575, "W" => 670)
Dict{String,Int64} with 6 entries:
"S" => 220
"U" => 400
"T" => 350
"W" => 670
"V" => 575
"R" => 100
We can also use SortedDict data type from the DataStructures.ji Julia package to make
sure that the dictionary remains sorted all the times. You can check the example below:
Example
julia> import DataStructures
106
Julia Programming
julia> first_dict = DataStructures.SortedDict("S" => 220, "T" => 350, "U" =>
400, "V" => 575, "W" => 670)
DataStructures.SortedDict{String,Int64,Base.Order.ForwardOrdering} with 5
entries:
"S" => 220
"T" => 350
"U" => 400
"V" => 575
"W" => 670
julia> first_dict["R"] = 100
100
julia> first_dict
DataStructures.SortedDict{String,Int64,Base.Order.ForwardOrdering} with 6
entries:
“R” => 100
“S” => 220
“T” => 350
“U” => 400
“V” => 575
“W” => 670
In the following example, we will be counting the words in a file name NLP.txtb(saved on
the desktop):
julia> f = open("C://Users//Leekha//Desktop//NLP.txt")
IOStream(<file C://Users//Leekha//Desktop//NLP.txt>)
julia> close(f)
We can see from the above output that wordlist is now an array of 984 elements.
To find out how many times the words appear, we can look up the words in the dictionary
as follows:
julia> wordcounts["natural"]
1
julia> wordcounts["processing"]
1
julia> wordcounts["and"]
14
108
Julia Programming
To find the most common words we can use collect() to convert the dictionary to an array
of tuples and then sort the array as follows:
109
Julia Programming
"of" => 47
"is" => 39
"a" => 28
"words" => 23
"meaning" => 23
"semantic" => 22
"lexical" => 21
"analysis" => 15
"and" => 14
"in" => 14
"be" => 13
"it" => 13
"example" => 13
"or" => 12
"word" => 12
"for" => 11
"are" => 11
"between" => 11
"as" => 11
⋮
"each" => 1
"river" => 1
"homonym" => 1
"classification" => 1
"analyze" => 1
"nocturnal" => 1
"axis" => 1
"concept" => 1
"deals" => 1
"larger" => 1
"destiny" => 1
"what" => 1
"reservation" => 1
"characterization" => 1
"second" => 1
"certitude" => 1
"into" => 1
110
Julia Programming
"compound" => 1
"introduction" => 1
We can use filter() function to find all the words that start with a particular alphabet (say
’n’).
Sets
Like an array or dictionary, a set may be defined as a collection of unique elements.
Following are the differences between sets and other kind of collections:
Creating a Set
With the help of Set constructor function, we can create a set as follows:
111
Julia Programming
Alternatively we can also use push!() function, as arrays, to add elements in sets as
follows:
Standard operations
Union, intersection, and difference are some standard operations we can do with sets. The
corresponding functions for these operations are union(), intersect(), and, setdiff().
Union
In general, the union (set) operation returns the combined results of the two statements.
Example
112
Julia Programming
julia> color_rainbow =
Set(["red","orange","yellow","green","blue","indigo","violet"])
Set{String} with 7 elements:
"indigo"
"yellow"
"orange"
"blue"
"violet"
"green"
"red"
Intersection
In general, an intersection operation takes two or more variables as inputs and returns
the intersection between them.
Example
Difference
In general, the difference operation takes two or more variables as an input. Then, it
returns the value of the first set excluding the value overlapped by the second set.
113
Julia Programming
Example
julia> dict2 = Dict(220 => "Y", 300 => "Z", 450 => "W")
Dict{Int64,String} with 3 entries:
450 => "W"
220 => "Y"
300 => "Z"
Union
julia> union(dict1, dict2)
4-element Array{Pair{Int64,String},1}:
100 => "X"
220 => "Y"
450 => "W"
300 => "Z"
Intersect
julia> intersect(dict1, dict2)
1-element Array{Pair{Int64,String},1}:
220 => "Y"
Difference
julia> setdiff(dict1, dict2)
1-element Array{Pair{Int64,String},1}:
114
Julia Programming
julia> findmin(dict1)
("X", 100)
115
14. Julia — Date & Time Julia Programming
Julia has a standard package named Dates which provides us the following two functions
to work with Dates and Times:
Using Dates
Import Dates
The difference between these two functions is that if we use import Dates function then
we will have to explicitly prefix Dates with every function, for example,
Dates.dayofweek(dt). On the other hand, if we use using Dates function then we do
not have to add the prefix Dates explicitly with every function because it will bring all
exported Dates function into main.
116
Julia Programming
AbstractTime
Tim Dat
e e
UTInstant
Abstract
DateTime
ISOCalend
er
TimePeriod DatePeriod
Hour
Secon Minute
d Week
Yea Day
Nanosecon Mont
d h
Millisecon Microsecon
d d
117
Julia Programming
Dates.Time: Accurate to nanosecond, this object represents a precise moment of the day.
Example
julia> rightnow = Dates.Time(Dates.now())
15:46:39.872
julia> Dates.now(Dates.UTC)
2020-09-22T10:18:32.008
julia> Dates.year(My_Birthday)
1984
julia> Dates.month(My_Birthday)
1
118
Julia Programming
julia> Dates.minute(now())
22
julia> Dates.hour(now())
19
julia> Dates.second(now())
19
julia> Dates.minute(rightnow)
46
julia> Dates.hour(rightnow)
15
julia> Dates.second(rightnow)
39
julia> Dates.dayofweek(My_Birthday)
2
julia> Dates.dayname(My_Birthday)
"Tuesday"
julia> Dates.yearmonthday(My_Birthday)
(1984, 1, 17)
julia> Dates.dayofweekofmonth(My_Birthday)
3
Date Arithmetic
It is also possible to do arithmetic on date/time as well as date objects. The most common
one is to find the difference between two such objects as shown in the below example:
Example
julia> today_date - My_Birthday
13409 days
We can also add and subtract periods of time to date and date/time objects as follows:
In the above example, we have added 20 years and 6 months to my birth date.
Range of Dates
Julia provides the facility to create range of dates by making iterable range objects. In the
example given below, we will be creating an iterator that yields the first day of every
month.
Example
julia> date_range = Dates.Date(2000,1,1):Dates.Month(1):Dates.Date(2020,1,1)
Date("2000-01-01"):Month(1):Date("2020-01-01")
From the above range object, we can find out which of these fall on weekdays. For this we
need to create an anonymous function to filter() which will test the day name against the
given day names:
120
Julia Programming
2019-01-01
2019-02-01
2019-03-01
2019-04-01
2019-05-01
2019-07-01
2019-08-01
2019-10-01
2019-11-01
2020-01-01
Formatting of Dates
Following table gives the date formatting codes with the help of which we can specify date
formats:
d Day Ex. 1 or 01
Example
julia> Dates.Date("Sun, 27 Sep 2020", "e, d u y")
2020-09-27
121
Julia Programming
Example
julia> Dates.now()
2020-09-27T13:34:03.49
The ceil() function will adjust the dates/time forward as given below:
Recurring Dates
If we want to find all the dates in a range of dates that satisfy some criteria, it is called
recurring dates. Let us understand with the help of following example:
122
Julia Programming
2000-10-01
2001-04-01
2001-07-01
2002-09-01
2002-12-01
2003-06-01
2004-02-01
2004-08-01
2005-05-01
2006-01-01
2006-10-01
2007-04-01
2007-07-01
⋮
2013-12-01
2014-06-01
2015-02-01
2015-03-01
2015-11-01
2016-05-01
2017-01-01
2017-10-01
2018-04-01
2018-07-01
2019-09-01
2019-12-01
Unix time
Unix time is another type of timekeeping in which the count of the number of seconds that
have elapsed since the birth of Unix (beginning of the year 1970). We will never observe
the end of Unix time because Julia store the count in a 64-bit integer.
The unix2datetime() function will convert a Unix time value to date/time object:
123
Julia Programming
julia> Dates.unix2datetime(time())
2020-09-10T09:54:52.894
Moments in time
DateTimes, in the field instant, are stored in milliseconds. We can obtain this value by
using Dates.value function as follows:
julia> moment=Dates.now()
2020-09-10T09:56:11.885
julia> Dates.value(moment)
63737767811885
julia> moment.instant
Dates.UTInstant{Millisecond}(Millisecond(63737767811885))
Example
julia> function foo(n)
for i in 1:n
x = sin(rand())
end
end
foo (generic function with 1 method)
124
15. Julia — Files I/O Julia Programming
foo = open("C://Users//Leekha//Desktop//NLP.txt")
It shows that now foo is the Julia’s connection to the text file namely NLP.txt on the disk.
Close(foo)
open("NLP.txt") do file
# here you can work with the open file
end
The advantage of wrapping file-processing functions inside do block is that the open file
will be automatically closed when this block finishes.
An example to keep some of the information like total time to read the file and total
lines in the files:
125
Julia Programming
Similarly, the below will store the contents of the file in ABC:
We can also read in the whole file as an array. Use readlines() as follows:
If you want to keep a track of which line you are on while reading the file, use the below
given approach:
126
Julia Programming
julia> open("C://Users//Leekha//Desktop//NLP.txt") do f
line = 1
while !eof(f)
x = readline(f)
println("$line $x")
line += 1
end
end
1 Natural Language Processing: Semantic Analysis
2
3 Introduction to semantic analysis:
4 The purpose of semantic analysis is to draw exact meaning, or you can say
dictionary meaning from the text. Semantic analyzer checks the text for
meaningfulness.
5 We know that lexical analysis also deals with the meaning of the words then
how semantic analysis is different from lexical analysis? The answer is that
Lexical analysis is based on smaller token but on the other side semantic
analysis focuses on larger chunks. That is why semantic analysis can be divided
into the following two parts:
6 Studying the meaning of individual word: It is the first part of the
semantic analysis in which the study of the meaning of individual words is
performed. This part is called lexical semantics.
7 Studying the combination of individual words: In this second part, the
individual words will be combined to provide meaning in sentences.
8 The most important task of semantic analysis is to get the proper meaning of
the sentence. For example, analyze the sentence “Ram is great.” In this
sentence, the speaker is talking either about Lord Ram or about a person whose
name is Ram. That is why the job, to get the proper meaning of the sentence, of
semantic analyzer is important.
9 Elements of semantic analysis:
10 Following are the elements of semantic analysis:……………………..
Functions Working
127
Julia Programming
Example
julia> for n in fieldnames(typeof(stat("C://Users//Leekha//Desktop//NLP.txt")))
println(n, ": ",
getfield(stat("C://Users//Leekha//Desktop//NLP.txt"),n))
end
device: 3262175189
inode: 17276
mode: 33206
nlink: 1
uid: 0
128
Julia Programming
gid: 0
rdev: 0
size: 6293
blksize: 4096
blocks: 16
mtime: 1.6017034024103658e9
ctime: 1.6017034024103658e9
Writing to files
A function writedlm(), a function in the DelimitedFiles package can be used to write
the contents of an object to a text file.
Example
julia> test_numbers = rand(10,10)
10×10 Array{Float64,2}:
0.457071 0.41895 0.63602 0.812757 0.727214 0.156181 0.023817
0.286904 0.488069 0.232787
0.623791 0.946815 0.757186 0.822932 0.791591 0.67814 0.903542
0.664997 0.702893 0.924639
129
Julia Programming
130
16. Julia Programming — Metaprogramming Julia Programming
Quoted expressions
As we discussed, with metaprogramming we can access the Julia code between two stages.
For this, Julia has ‘:’ colon prefix operator. With the help of colon operator, Julia store an
unevaluated but parsed expression.
Example
julia> ABC = 100
100
julia> :ABC
:ABC
Here, :ABC is quoted or unevaluated symbol for Julia i.e. ‘ABC ‘ is an unevaluated symbol
rather than having the value 100.
julia> :(100-50)
:(100 - 50)
Alternatively, we can also use quote…end keywords to enclose and quote an expression
as follows:
131
Julia Programming
julia> quote
100 - 50
end
quote
#= REPL[43]:2 =#
100 - 50
end
Check this also:
julia> expression = quote
for x = 1:5
println(x)
end
end
quote
#= REPL[46]:2 =#
for x = 1:5
#= REPL[46]:3 =#
println(x)
end
end
julia> typeof(expression)
Expr
Evaluated expressions
Once you parsed the expression, there is a way to evaluate the expression also. We can
use the function eval() for this purpose as follows:
julia> eval(:ABC)
100
julia> eval(:(100-50))
50
julia> eval(expression)
132
Julia Programming
1
2
3
4
5
Example
julia> dump(:(1 * cos(pi/2)))
Expr
head: Symbol call
args: Array{Any}((3,))
1: Symbol *
2: Int64 1
3: Expr
head: Symbol call
args: Array{Any}((2,))
1: Symbol cos
2: Expr
head: Symbol call
args: Array{Any}((3,))
1: Symbol /
2: Symbol pi
3: Int64 2
Expression interpolation
Any Julia code which has string or expression is usually unevaluated but with the help of
dollar ($) sign (string interpolation operator), we can evaluate some of the code. The Julia
code will be evaluated and inserts the resulting value into the string when the string
interpolation operator is used inside a string.
Example
133
Julia Programming
Similarly, we can use this string interpolation operator to include the results of executing
Julia code interpolated into unevaluated expression:
Macros
We are now aware of creating and handling unevaluated expressions. In this section, we
will understand how we can modify them. Julia provides macro that accepts an
unevaluated expression as input and generates a new output expression.
If we talk about its working, Julia first parses and evaluates the macro, and then the
processed code produced by macro will be evaluated like an ordinary expression.
The syntax of defining a macro is very similar to that of a function. Following is the
definition of macro that will print out the contents of the things we pass to it:
We can run the macros by preceding the name of the macro with the @ prefix:
julia> @x 500
500
julia> @x "Tutorialspoint.com"
"Tutorialspoint.com"
Julia has eval() function and a macro called @eval. Let us see example to know their
differences:
134
Julia Programming
julia> eval(ABC)
150
The above output shows that the eval() function expands the expression and evaluates it.
Expanding Macros
The macroexpand() function returns the expanded format (used by the Julia compiler
before it is finally executed) of the specified macro.
Example
julia> macroexpand(Main, quote @p 1 + 4 - 6 * 7 / 8 % 9 end)
Any[:-, :(1 + 4), :(((6 * 7) / 8) % 9)]
quote
#= REPL[69]:1 =#
(1 + 4) - ((6 * 7) / 8) % 9
end
135
17. Julia Programming — Plotting Julia Programming
Julia has various packages for plotting and before starting making plots, we need to first
download and install some of them as follows:
Plotting a function
For plotting a function, we need to switch back to PyPlot back-end as follows:
julia> pyplot()
Plots.PyPlotBackend()
Here we will be plotting the equation of Time graph which can be modeled by the following
function:
136
Julia Programming
Packages
Everyone wants a package that helps them to draw quick plots by text rather than
graphics.
UnicodePlots
Julia provides one such package called UnicodePlots which can produce the following:
scatter plots
line plots
bar plots
staircase plots
histograms
sparsity patterns
density plots
Example
Following Julia example generates a line chart using UnicodePlots.
137
Julia Programming
Example
Following Julia example generates a density chart using UnicodePlots.
138
Julia Programming
VegaLite
This Julia package is a visualization grammar which allows us to create visualization in a
web browser window. With this package, we can:
Area plots
Bar plots/Histograms
Line plots
Scatter plots
Pie/Donut charts
Waterfall charts
Worldclouds
139
Julia Programming
Example
Following Julia example generates a Pie chart using VegaLite.
julia> P = pie(X,Y)
140
18. Julia Programming — Data Frames Julia Programming
anscombe = DataFrame(
[10 10 10 8 8.04 9.14 7.46 6.58;
8 8 8 8 6.95 8.14 6.77 5.76;
13 13 13 8 7.58 8.74 12.74 7.71;
9 9 9 8 8.81 8.77 7.11 8.84;
11 11 11 8 8.33 9.26 7.81 8.47;
14 14 14 8 9.96 8.1 8.84 7.04;
6 6 6 8 7.24 6.13 6.08 5.25;
4 4 4 19 4.26 3.1 5.39 12.5;
12 12 12 8 10.84 9.13 8.15 5.56;
7 7 7 8 4.82 7.26 6.42 7.91;
5 5 5 8 5.68 4.74 5.73 6.89]);
141
Julia Programming
├─────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼──
───────┤
│ 1 │ 10.0 │ 10.0 │ 10.0 │ 8.0 │ 8.04 │ 9.14 │ 7.46 │
6.58 │
│ 2 │ 8.0 │ 8.0 │ 8.0 │ 8.0 │ 6.95 │ 8.14 │ 6.77 │
5.76 │
│ 3 │ 13.0 │ 13.0 │ 13.0 │ 8.0 │ 7.58 │ 8.74 │ 12.74 │
7.71 │
│ 4 │ 9.0 │ 9.0 │ 9.0 │ 8.0 │ 8.81 │ 8.77 │ 7.11 │
8.84 │
│ 5 │ 11.0 │ 11.0 │ 11.0 │ 8.0 │ 8.33 │ 9.26 │ 7.81 │
8.47 │
│ 6 │ 14.0 │ 14.0 │ 14.0 │ 8.0 │ 9.96 │ 8.1 │ 8.84 │
7.04 │
│ 7 │ 6.0 │ 6.0 │ 6.0 │ 8.0 │ 7.24 │ 6.13 │ 6.08 │
5.25 │
│ 8 │ 4.0 │ 4.0 │ 4.0 │ 19.0 │ 4.26 │ 3.1 │ 5.39 │
12.5 │
│ 9 │ 12.0 │ 12.0 │ 12.0 │ 8.0 │ 10.84 │ 9.13 │ 8.15 │
5.56 │
│ 10 │ 7.0 │ 7.0 │ 7.0 │ 8.0 │ 4.82 │ 7.26 │ 6.42 │
7.91 │
│ 11 │ 5.0 │ 5.0 │ 5.0 │ 8.0 │ 5.68 │ 4.74 │ 5.73 │
6.89 │
We assigned the DataFrame to a variable named Anscombe, convert them to an array and
then rename columns.
Collected Datasets
We can also use another dataset package named RDatasets package. It contains several
other famous datasets including Anscombe’s. Before we start using it, we need to first
download and install it as follows:
142
Julia Programming
Empty DataFrames
We can also create DataFrames by simply providing the information about rows, columns
as we give in an array.
Example
julia> empty_df = DataFrame(X = 1:10, Y = 21:30)
10×2 DataFrame
│ Row │ X │ Y │
│ │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1 │ 1 │ 21 │
│ 2 │ 2 │ 22 │
│ 3 │ 3 │ 23 │
│ 4 │ 4 │ 24 │
│ 5 │ 5 │ 25 │
│ 6 │ 6 │ 26 │
│ 7 │ 7 │ 27 │
│ 8 │ 8 │ 28 │
│ 9 │ 9 │ 29 │
│ 10 │ 10 │ 30 │
To create completely empty DataFrame, we only need to supply the Column Names and
define their types as follows:
V=Float64[])
0×5 DataFrame
mean
std
min
q25
median
q75
max
eltype
nunique
first
last
nmissing
144
Julia Programming
Example
julia> describe(anscombe, :mean, :std, :min, :median, :q25)
8×6 DataFrame
│ Row │ variable │ mean │ std │ min │ median │ q25 │
│ │ Symbol │ Float64 │ Float64 │ Real │ Float64 │ Float64 │
├─────┼──────────┼─────────┼─────────┼──────┼─────────┼─────────┤
│ 1 │ X1 │ 9.0 │ 3.31662 │ 4 │ 9.0 │ 6.5 │
│ 2 │ X2 │ 9.0 │ 3.31662 │ 4 │ 9.0 │ 6.5 │
│ 3 │ X3 │ 9.0 │ 3.31662 │ 4 │ 9.0 │ 6.5 │
│ 4 │ X4 │ 9.0 │ 3.31662 │ 8 │ 8.0 │ 8.0 │
│ 5 │ Y1 │ 7.50091 │ 2.03157 │ 4.26 │ 7.58 │ 6.315 │
│ 6 │ Y2 │ 7.50091 │ 2.03166 │ 3.1 │ 8.14 │ 6.695 │
│ 7 │ Y3 │ 7.5 │ 2.03042 │ 5.39 │ 7.11 │ 6.25 │
│ 8 │ Y4 │ 7.50091 │ 2.03058 │ 5.25 │ 7.04 │ 6.17 │
145
Julia Programming
2×5 DataFrame
│ Row │ variable │ mean │ std │ median │ q25 │
│ │ Symbol │ Float64 │ Float64 │ Float64 │ Float64 │
├─────┼──────────┼─────────┼─────────┼─────────┼─────────┤
│ 1 │ X4 │ 9.0 │ 3.31662 │ 8.0 │ 8.0 │
│ 2 │ Y4 │ 7.50091 │ 2.03058 │ 7.04 │ 6.17 │
Let us reveal the true purpose of Anscombe, i.e., plot the four sets of its quartet as follows:
julia> @df anscombe scatter([:X1 :X2 :X3 :X4], [:Y1 :Y2 :Y3 :Y4],
smooth=true,
line = :red,
linewidth = 2,
title= ["X$i vs Y$i" for i in (1:4)'],
legend = false,
layout = 4,
xlimits = (2, 20),
ylimits = (2, 14))
146
Julia Programming
Now let us create a liner regression model by specifying a formula using the @formula
macro and supplying columns names as well as name of the DataFrame. An example for
the same is given below:
Y1 ~ 1 + X1
Coefficients:
───────────────────────────────────────────────────────────────────────
Coef. Std. Error t Pr(>|t|) Lower 95% Upper 95%
───────────────────────────────────────────────────────────────────────
(Intercept) 3.00009 1.12475 2.67 0.0257 0.455737 5.54444
X1 0.500091 0.117906 4.24 0.0022 0.23337 0.766812
───────────────────────────────────────────────────────────────────────
Let us check the summary and the coefficient of the above created linear regression
model:
julia> summary(linearregressionmodel)
"StatsModels.TableRegressionModel{LinearModel{GLM.LmResp{Array{Float64,1}},GLM.
DensePredChol{Float64,LinearAlgebra.Cholesky{Float64,Array{Float64,2}}}},Array{
Float64,2}}"
julia> coef(linearregressionmodel)
2-element Array{Float64,1}:
3.0000909090909054
0.5000909090909096
Now let us produce a function for the regression line. The form of the function is y = ax
+c.
147
Julia Programming
Once we have the function that describes the regression line, we can draw a plot as
follows:
5×5 DataFrame
│ Row │ Number │ Name │ AtomicWeight │ Symbol │ Discovered │
│ │ Int64 │ String │ Float64 │ String │ Int64? │
├─────┼────────┼──────────┼──────────────┼────────┼────────────┤
│ 1 │ 3 │ Lithium │ 6.941 │ Li │ 1817 │
│ 2 │ 5 │ Boron │ 10.811 │ B │ 1808 │
│ 3 │ 7 │ Nitrogen │ 14.0067 │ N │ 1772 │
│ 4 │ 8 │ Oxygen │ 15.9994 │ O │ 1774 │
│ 5 │ 20 │ Calcium │ 40.078 │ Ca │ missing │
julia> describe(testdf)
5×8 DataFrame
│ Row │ variable │ mean │ min │ median │ max │ nunique │ nmissing
│ eltype │
│ │ Symbol │ Union… │ Any │ Union… │ Any │ Union… │ Union…
│ Type │
├─────┼──────────────┼─────────┼───────┼─────────┼────────┼─────────┼──────────
┼───────────────────────┤
│ 1 │ Number │ 8.6 │ 3 │ 7.0 │ 20 │ │
│ Int64 │
│ 2 │ Name │ │ Boron │ │ Oxygen │ 5 │
│ String │
│ 3 │ AtomicWeight │ 17.5672 │ 6.941 │ 14.0067 │ 40.078 │ │
│ Float64 │
│ 4 │ Symbol │ │ B │ │ O │ 5 │
│ String │
│ 5 │ Discovered │ 1792.75 │ 1772 │ 1791.0 │ 1817 │ │ 1
│ Union{Missing, Int64} │
Julia provides a special datatype called Missing to address such issue. This datatype
indicates that there is not a usable value at this location. That is why the DataFrames
149
Julia Programming
packages allow us to get most of our datasets and make sure that the calculations are not
tampered due to missing values.
Example
julia> for row in 1:nrows
for col in 1:ncols
if ismissing(testdf [row,col])
println("$(names(testdf)[col]) value for $(testdf[row,:Name])
is missing!")
end
end
end
Repairing DataFrames
We can use the following code to change values that are not acceptable like “n/a”, “0”,
“missing”. The below code will look in every cell for above mentioned non-acceptable
values.
Example
julia> for row in 1:size(testdf, 1) # or nrow(testdf)
for col in 1:size(testdf, 2) # or ncol(testdf)
println("processing row $row column $col ")
temp = testdf [row,col]
if ismissing(temp)
println("skipping missing")
elseif temp == "n/a" || temp == "0" || temp == 0
testdf [row, col] = missing
println("changed row $row column $col ")
end
end
end
processing row 1 column 1
processing row 1 column 2
150
Julia Programming
completecases()
The completecases() function is used to find the maximum value of the column that
contains the missing value.
Example
151
Julia Programming
dropmissing()
The dropmissing() function is used to get the copy of DataFrames without having the
missing values.
Example
julia> dropmissing(testdf)
4×5 DataFrame
│ Row │ Number │ Name │ AtomicWeight │ Symbol │ Discovered │
│ │ Int64 │ String │ Float64 │ String │ Int64 │
├─────┼────────┼──────────┼──────────────┼────────┼────────────┤
│ 1 │ 3 │ Lithium │ 6.941 │ Li │ 1817 │
│ 2 │ 5 │ Boron │ 10.811 │ B │ 1808 │
│ 3 │ 7 │ Nitrogen │ 14.0067 │ N │ 1772 │
│ 4 │ 8 │ Oxygen │ 15.9994 │ O │ 1774 │
Modifying DataFrames
The DataFrames package of Julia provides various methods using which you can add,
remove, rename columns, and add/delete rows.
Adding Columns
We can use hcat() function to add a column of integers to the DataFrame. It can be used
as follows:
But as you can notice that we haven’t changed the DataFrame or assigned any new
DataFrame to a symbol. We can add another column as follows:
152
Julia Programming
2300.0
-209.86
-222.65
839.0
julia> testdf
5×6 DataFrame
│ Row │ Number │ Name │ AtomicWeight │ Symbol │ Discovered │ MP │
│ │ Int64 │ String │ Float64 │ String │ Int64? │ Float64 │
├─────┼────────┼──────────┼──────────────┼────────┼────────────┼─────────┤
│ 1 │ 3 │ Lithium │ 6.941 │ Li │ 1817 │ 180.7 │
│ 2 │ 5 │ Boron │ 10.811 │ B │ 1808 │ 2300.0 │
│ 3 │ 7 │ Nitrogen │ 14.0067 │ N │ 1772 │ -209.86 │
│ 4 │ 8 │ Oxygen │ 15.9994 │ O │ 1774 │ -222.65 │
│ 5 │ 20 │ Calcium │ 40.078 │ Ca │ missing │ 839.0 │
We have added a column having melting points of all the elements to our test DataFrame.
Removing Columns
We can use select!() function to remove a column from the DataFrame. It will create a
new DataFrame that contains the selected columns, hence to remove a particular column,
we need to use select!() with Not. It is shown in the given example:
Renaming Columns
We can use rename!() function to rename a column in the DataFrame. We will be
renaming the AtomicWeight column to AW as follows:
5×5 DataFrame
│ Row │ Number │ Name │ AW │ Symbol │ Discovered │
│ │ Int64 │ String │ Float64 │ String │ Int64? │
├─────┼────────┼──────────┼─────────┼────────┼────────────┤
│ 1 │ 3 │ Lithium │ 6.941 │ Li │ 1817 │
│ 2 │ 5 │ Boron │ 10.811 │ B │ 1808 │
│ 3 │ 7 │ Nitrogen │ 14.0067 │ N │ 1772 │
│ 4 │ 8 │ Oxygen │ 15.9994 │ O │ 1774 │
│ 5 │ 20 │ Calcium │ 40.078 │ Ca │ missing │
Adding rows
We can use push!() function with suitable data to add rows in the DataFrame. In the
below given example we will be adding a row having element Cooper:
Example
Deleting rows
We can use deleterows!() function with suitable data to delete rows from the DataFrame.
In the below given example we will be deleting three rows (4th, 5th,and 6th) from our test
data frame:
Example
154
Julia Programming
Example
julia> testdf[:, :AW] .< 10
3-element BitArray{1}:
1
0
0
Sorting
To sort the values in DataFrame, we can use sort!() function. We need to give the columns
on which we want to sort.
Example
155
19. Julia Programming — Working with Datasets Julia Programming
CSV files
As we know that CSV (Comma Separated Value) file is a plain text file which uses commas
to separate fields and values of those fields. The extension of these files is .CSV. We have
various methods provided by Julia programming language to perform operations on CSV
files.
using pkg
pkg.add("CSV")
Reading data
To read data from a CSV file in Julia we need to use read() method from CSV package as
follows:
├─────┼───────┼───────────────┼────────────
──┼───────────────┼──────────────┼─────────
───────┤
156
Julia Programming
julia> CSV.read("1234.csv")
5×3 DataFrame
│ Row │ Name │ RollNo │ Marks │
│ │ String │ Int64 │ Int64 │
├─────┼──────────┼────────┼───────┤
│ 1 │ Gaurav │ 1 │ 54 │
│ 2 │ Rahul │ 2 │ 67 │
│ 3 │ Aarav │ 3 │ 90 │
│ 4 │ Raman │ 4 │ 23 │
│ 5 │ Ravinder │ 5 │ 95 │
HDF5
The full form of HDF5 is Hierarchical Data Format v5. Following are some of its properties:
158
Julia Programming
mode Meaning
"r" read-only
read-write
"r+"
It will preserve any existing contents.
read-write
read-write
"w"
It will destroy any existing contents.
The above command will produce an object of type HDF5File and a subtype of the abstract
type DataFile.
close(fid)
Obj1 = fid[“object1”]
159
Julia Programming
Reading data
A group “g” containing a dataset with path “dtset” and we have opened dataset as dset1
= g[dtset]. We can read the information in following ways:
ABC = read(dset1)
ABC = read(g, "dtset")
Asub = dset1[2:3, 1:3]
Writing data
We can create the dataset as follows:
g["dset1"] = rand(3,5)
write(g, "dset1", rand(3,5))
XML files
Here we will be discussing about LightXML.jl package which is a light-weight Julia
wrapper for libxml2. It provides the following functionalities:
Example
Suppose we have an xml file named new.xml as follows:
<Hello>
<to>Gaurav</to>
<from>Rahul</from>
<heading>Reminder to meet</heading>
<body>Friend, Don't forget to meet this weekend!</body>
</Hello>
160
Julia Programming
161
Julia Programming
RDatasets
Julia has RDatasets.jl package providing easy way to use and experiment with most of the
standard data sets which are available in the core of R. To load and work with one of the
datasets included in RDatasets packages, we need to install RDatasets as follows:
162
Julia Programming
Statistics in Julia
To work with statistics, Julia has StatsBase.jl package providing easy way to do simple
statistics. To work with statistics, we need to install StatsBase package as follows:
Simple Statistics
Julia provides methods to define weights and calculate mean.
julia> WV = Weights([10.,11.,12.])
3-element Weights{Float64,Float64,Array{Float64,1}}:
10.0
11.0
12.0
You can use the isempty() function to check whether the weight vector is empty or not:
julia> isempty(WV)
false
We can check the type of weight vectors with the help of eltype() function as follows:
julia> eltype(WV)
Float64
We can check the length of the weight vectors with the help of length() function as follows:
julia> length(WV)
3
164
Julia Programming
julia> geomean(A)
5.555368605381863
General mean: We can use mean() function to calculate the general mean.
julia> mean(A)
6.25
Descriptive Statistics
It is that discipline of statistics in which information is extracted and analyzed. This
information explains the essence of data.
Calculating variance
We can use var() function to calculate the variance of a vector as follows:
165
Julia Programming
julia> std(B)
1.5811388300841898
julia> std(B,a)
1.4373989364401725
julia> mean_and_std(B,a)
(2.5454545454545454, 1.4373989364401725)
julia> mean_and_var(B,a)
(2.5454545454545454, 2.066115702479339)
166
Julia Programming
Taking random samples is the simplest way of doing sampling. In this we draw a random
element from the array, i.e., the population set. The function for this purpose is sample().
Example
julia> A = [8.,12.,23.,54.5]
4-element Array{Float64,1}:
8.0
12.0
23.0
54.5
julia> sample(A)
12.0
Example
julia> A = [8.,12.,23.,54.5]
4-element Array{Float64,1}:
8.0
12.0
23.0
54.5
julia> sample(A, 2)
2-element Array{Float64,1}:
23.0
54.5
We can also write the sampled elements to pre-allocated elements of length “n”. The
function to do this task is sample!().
Example
julia> B = [1., 2., 3., 4., 5.];
julia> X = [2., 1., 3., 2., 5.];
julia> sample!(B,X)
5-element Array{Float64,1}:
2.0
2.0
167
Julia Programming
4.0
1.0
3.0
Another way is to do direct sampling which will randomly picks the numbers from a
population set and stores them in another array. The function to do this task is
direct_sample!().
Example
julia> StatsBase.direct_sample!(B, X)
5-element Array{Float64,1}:
1.0
4.0
4.0
4.0
5.0
Knuth’s algorithms is one other way in which random sampling is done without replcement.
Example
julia> StatsBase.knuths_sample!(B, X)
5-element Array{Float64,1}:
5.0
3.0
4.0
2.0
1.0
168
20. Julia Programming — Modules and Packages Julia Programming
The modules in Julia programming language are used to group together the related
functions and other definitions. The structure of a module is given below:
module ModuleName
end
We can define and put functions, type definitions, and so on in between above two lines.
Installing Modules
Julia’s package manager can be used to download and install a particular package. To
enter the package manage from REPL, type ] (right bracket). Once entering the package
manager, you need to type the following command:
The above command will add DataFrames package to Julia’s environment. The (@v1.5)
in the prompt tells us that we are working in the default project, "v1.5", in
~/.julia/environments/.
Using Modules
Once installed, it is time to start using the functions and definitions from the installed
module. For this we need to tell Julia programming language to make code available for
our current session. Use using statement which will accept the names of one or more
installed modules.
Example
169
Julia Programming
│ │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1 │ 1 │ 21 │
│ 2 │ 2 │ 22 │
│ 3 │ 3 │ 23 │
│ 4 │ 4 │ 24 │
│ 5 │ 5 │ 25 │
│ 6 │ 6 │ 26 │
│ 7 │ 7 │ 27 │
│ 8 │ 8 │ 28 │
│ 9 │ 9 │ 29 │
│ 10 │ 10 │ 30 │
Import
Like using, import can also be used for modules. The only difference is that import lets
you decide how you would like to access the functions inside the module. In the below
example, we have two different functions in a module. Let us see how we can import them:
Example
function foo1()
println("this is first function")
end
function foo2()
println("this is second function")
end
end
Main.first_module
julia> foo1()
ERROR: foo1 not defined
170
Julia Programming
julia> first_module.foo1()
"this is first function"
You can notice that the function foo1() can only be accessed if it is used with module
prefix. It is because the first_module was loaded using import command rather than
using command.
Include
What if you want to use the code from other files that are not contained in the modules?
For this you can use include() function which will evaluate the contents of the file in the
context of the current module. It will search the relative path of the source file from which
it is called.
Packages
Use status command in Julia package environment to see all the packages you have
installed.
171
Julia Programming
Structure of a package
As we know that Julia uses git for organizing as well controlling the packages. All the
packages are stored with .ji prefix. Let us see the structure of Calculus package:
Calculus.jl/
src/
Calculus.jl
module Calculus
import Base.ctranspose
export derivative, check_gradient,
...
include("derivative.jl")
include("check_derivative.jl")
include("integrate.jl")
end
derivative.jl
function derivative()
...
end
...
check_derivative.jl
function check_derivative(f::...)
...
end
...
integrate.jl
function adaptive_simpsons_inner(f::Funct
...
end
...
symbolic.jl
export processExpr, BasicVariable, ...
import Base.show, ...
type BasicVariable <: AbstractVariable
...
end
function process(x::Expr)
...
172
Julia Programming
end
...
test/
runtests.jl
using Calculus
using Base.Test
tests = ["finite_difference", ...
for t in tests
include("$(t).jl")
end
...
finite_difference.jl
@test ...
...
173
21. Julia Programming — Working with Graphics Julia Programming
This chapter discusses how to plot, visualize and perform other (graphic) operations on
data using various tools in Julia.
Example
The following is an example to draw a line:
julia> cr = CairoContext(img);
julia> save(cr);
julia> fill(cr);
julia> restore(cr);
julia> save(cr);
Now, we will define the points and draw a line through those points:
174
Julia Programming
julia> stroke_preserve(cr);
julia> restore(cr);
julia> show_text(cr,"Line_Figure")
julia> write_to_png(c,"Line_Figure.png");
Output
175
Julia Programming
Example
julia> x = range(0, stop=3pi, length=100);
julia> c = cos.(x);
julia> s = sin.(x);
julia> p = FramedPlot(
title="Winston Graphics!",
xlabel="\\Sigma x^2_i",
ylabel="\\Theta_i")
Data Visualization
Data visualization may be defined as the presentation of data in a variety of graphical as
well as pictorial formats such as pie and bar charts.
176
Julia Programming
Gadfly
Gadfly is a powerful Julia package for data visualization and an implementation of the
“grammar of graphics” style. It is based on the same principal as ggplot2 in R. For using
it, we need to first add it with the help of Julia package manager.
Example
To use Gadfly, we first need to use RDatasets package so that we can get some datasets
to work with. In this example, we will be using iris dataset:
julia> first(iris,10)
10×5 DataFrame
│ Row │ SepalLength │ SepalWidth │ PetalLength │ PetalWidth │ Species │
│ │ Float64 │ Float64 │ Float64 │ Float64 │ Cat… │
├─────┼─────────────┼────────────┼─────────────┼────────────┼─────────┤
│ 1 │ 5.1 │ 3.5 │ 1.4 │ 0.2 │ setosa │
│ 2 │ 4.9 │ 3.0 │ 1.4 │ 0.2 │ setosa │
│ 3 │ 4.7 │ 3.2 │ 1.3 │ 0.2 │ setosa │
│ 4 │ 4.6 │ 3.1 │ 1.5 │ 0.2 │ setosa │
│ 5 │ 5.0 │ 3.6 │ 1.4 │ 0.2 │ setosa │
│ 6 │ 5.4 │ 3.9 │ 1.7 │ 0.4 │ setosa │
│ 7 │ 4.6 │ 3.4 │ 1.4 │ 0.3 │ setosa │
│ 8 │ 5.0 │ 3.4 │ 1.5 │ 0.2 │ setosa │
│ 9 │ 4.4 │ 2.9 │ 1.4 │ 0.2 │ setosa │
│ 10 │ 4.9 │ 3.1 │ 1.5 │ 0.1 │ setosa │
Now let us plot a scatter plot. We will be using the variables namely SepalLength and
SepalWidth. For this, we need to set the geometry element using Geom.point as follows:
177
Julia Programming
Similarly we can add some more geometries like geom.line to produce more layers in the
plot:
178
Julia Programming
179
Julia Programming
Compose
Compose is a declarative vector graphics system. It is also written by Daniel Jones as a
part of the Gadfly system. In Compose, the graphics are defined using a tree structure
and the primitives can be classified as follows:
Form: It represents a leaf node which defines some geometry such as a circle or
line.
Property: It represents a leaf node that modifies how its parent’s subtree is drawn.
For example, fill color and line width.
Example
The below example will draw a simple image:
Now let us form more complex trees by grouping subtrees with brackets:
180
Julia Programming
Graphics Engines
In this section, we shall discuss various graphic engines used in Julia.
PyPlot
PyPlot, arose from the previous development of the PyCall module, provides a Julia
interface to the Matplotlib plotting library from Python. It uses the PyCall package to call
Matplotlib directly from Julia. To work with PytPlot, we need to do the following setup:
julia> Conda.add("matplotlib")
Once you are done with this setup, you can simply import PyPlot by using PyPlot
command. It will let you make calling functions in matplotlib.pyplot.
Example
This example, from PyPlot documentation, will create a sinusoidally modulated sinusoid:
1-element Array{PyCall.PyObject,1}:
PyObject <matplotlib.lines.Line2D object at 0x00000000323405E0>
181
Julia Programming
The PyPlot package can also be used for 3d plotting and for this it can import functions
from Matplotlib’s mplot3d toolkit. We can create 3d plots directly also by calling some
corresponding methods such as bar3d, plot_surface, plot3d, etc., of Axes3d.
julia> surf(rand(20,30))
182
Julia Programming
Gaston
Gaston is another useful package for plotting. This plotting package provides an interface
to gnuplot.
It can plot using graphical windows, and with mouse interaction, it can keep
multiple plots active at one time.
It can plot directly to the REPL.
It can also plot in Jupyter and Juno.
It supports popular 2-dimensional plots such as stem, step, histograms, etc.
It also supports popular 3-dimensional plots such as surface, contour, and
heatmap.
It takes around five seconds to load package, plot, and save to pdf.
Example
A simple 2-D plot with the help of Gaston is shown below:
julia> x = 0:0.01:1
0.0:0.01:1.0
julia> plot(x, sin.(2π*5*t))
183
Julia Programming
PyPlot can also be used to plot 3-d plots. Example is given below:
julia> a = b = -10:0.30:10
-10.0:0.3:9.8
184
Julia Programming
PGF Plots
PGFPlots, unlike Gaston, is relatively a new package for plotting. This plotting package
uses the pgfplots LaTex routines to produce the plots. It can easily integrate with IJulia,
outputting SVG images to notebook. To work with it, we need to install the following
dependencies:
Once you are done with these installations, you are ready to use PGFPlots.
Example
185
Julia Programming
In this example, we will be generating multiple curves on the same axis and assign their
legend entries in LaTex format:
186
22. Julia Programming — Networking Julia Programming
The advantage is that the programmer does not need to think about the underlying
asynchronous operations. Before getting deep into this, we should know the concept of
well-known ports.
Well-known ports
The concept of well-known ports and networked services on them was introduced in early
1980s by Berkeley development. It was first introduced to Unix. The basic idea behind this
was:
Unreliable
The concept of unreliable socket rests in the fact that some requests which if not serviced,
will be ignored, and retired. Example, requesting the network time from NNTP server. All
these kinds of sockets are connectionless and operating via UDP (User Datagram Protocol).
Reliable
187
Julia Programming
The concept of reliable sockets is opposite to unreliable sockets. They are connection full
and operate via TCP (Transmission Control Protocol).
Julia supports both these sockets (UDP and TCP) and the source code is provided in
socket.jl and streams.jl base modules.
Example
In the example given below, we will be creating a simple server involving TCP sockets:
julia> connect(2000)
This is TCP server example
Named Pipes
Named pipes or UNIX domain sockets is a FIFO(First-in, First-out) stream and an extension
to the traditional pipe mechanism on Unix and OS X. It is also available on Windows and
has a specific pattern for the name prefix (\\.\pipe\). It is a communication channel which
uses a special file.
Example
julia> connect(2000)
188
Julia Programming
Example
The following example will return a random quote as plain text from a text file:
julia> web_server(8080)
Task (runnable) @0x0000000014bae570
189
Julia Programming
Pkg.add(“Requests”)
Next, import the necessary modules namely get and post as follows:
Use GET request to request data from a specified web browser as follows:
If you want to request from a specified web page inside the website, use the query
parameter as follows:
We can also set the timeouts for the GET request as follows:
We can use the below command to avoid getting your request repeatedly redirected to
different websites:
Using the below command prevents the site from redirecting your GET request:
Using the below command, we can send data to web browser through the POST request:
Let us see how we can send data such as session cookies to web browser through the
POST request:
190
Julia Programming
file = "book.jl"
post("url of the website"; files = [FileParam(file), "text/julia",
"file_name", "file_name.jl"])
WebSockets
We are familiar with the method called AJAX (Asynchronous JavaScript and XML). The
example for this method can be the process where we type in the search box and the
server returns a set of suggestions and they change as the search term is refined. With
this, it is clear that the overhead usage of HTTP protocols is very high.
Web Sockets, which combine the parts of UDP and TCP, are the way to overcome this
problem. Hence, web sockets are message-based such as UDP and reliable as TCP. It uses
normal HTTP/HTTPS ports, i.e., port 80 and port 443 respectively. They are ideal for
vehicles for chat services. Julia provides a package named websockets.jl.
Messaging
Julia supports the following messaging methods:
E-mail
Email is one of the oldest messaging methods. Email messaging can be done in two ways:
Sending e-mails: It happens on well-known port 25. Some other ports such as
465 and 587 can also be used for this purpose. SMTP (Simple Mail Transport
Protocol) that consists of formulating a message the SMTP server can understand
is used for sending emails. To:, From:, and Subject:, all together with the
message should be deposited in the mail service’s outbound queue.
Example
Following code can be used to send emails:
using SMTPClient
opt = SendOptions(
isSSL = true,
username = "g*****@gmail.com",
passwd = "yourgmailpassword")
body = IOBuffer(
191
Julia Programming
Twitter
Apart from E-mail, there are other systems that send SMS textual information. One of
them is Twitter. Julia provides a package named Twitter.jl to work with Twitter API. To
work with Twitter on Julia, we need to authenticate. For authentication, we need to first
create an application on dev.twitter.com. After setting up the application, we will be able
to access our consumer_key, consumer_token, oauth_token, and oauth_secret.
using Twitter
twitterauth("1234567nOtp...",
"1234sES96S...",
"45750-Hjas...",
"Uonhjlmkmj...")
If you want to say hello to all your Twitter followers, use the following code:
post_status_update("Hello")
And if you want to search the tweets containing the hashtag say #TutorialsPoint, the
function call will be as follows:
my_tweets = get_search_tweets("#TutorialsPoint")
The Twitter API bydefault will return the 15 most recent tweets containing the above
searched hastag.
Suppose if you want to return the most recent 50 tweets, you can pass the “count” as
follows:
192
Julia Programming
df_tweets = DataFrame(my_tweets_50)
Cloud Services
Julia offers the following cloud services:
Includes automated code generation to ensure all new AWS services are available.
julia> Pkg.add("AWS")
AWS.jl package can be used with both low-level and high-level API requests. Following are
the services supported:
EC2
S3
SQS
Auto Scaling
AWSEnv
The structure of AWSEnv is as follows:
type AWSEnv
aws_id::String # AWS Access Key id
aws_seckey::String # AWS Secret key for signing requests
aws_token::String # AWS Security Token for temporary credentials
region::String # region name
ep_scheme::String # URL scheme: http or https
ep_host::String # region endpoint (host)
ep_path::String # region endpoint (path)
sig_ver::Int # AWS signature version (2 or 4)
timeout::Float64 # request timeout in seconds, Default is 0.0
dry_run::Bool # If true, no actual request will be made
dbg::Bool # print request and raw response to screen
end
193
Julia Programming
Constructors
Following are the constructors in AWS:
Here,
Binary Dependencies
Following must be installed before using AWS:
libz
libxm2
Prerequisites
Following are some prerequisites for Google Cloud:
You need to create a new project. Click on the Project drop-down menu at the
top of the page.
You need to first get the credentials from your GCP credentials page, that are
associated with your project, as a JSON file.
Pkg.add(“GoogleCloud”)
194
Julia Programming
using GoogleCloud
Now we need to load the service account credentials obtained from Google account:
set_session!(storage, session)
You can list all the buckets in your existing project as shown below:
195
23. Julia Programming — Databases Julia Programming
Following are the four mechanisms for interfacing with a particular database system:
Second method is via an intermediate abstract layer. This abstract layer will
communicate with the database API via a driver. Some example of such drivers are
ODBC, JDBC, and Database Interface (DBI).
Third approach is to use Python module for a specific database system. PyCall
package will be used to call routines in the Python module. It will also handle the
interchange of datatypes between Python and Julia.
The fourth method is sending messages to the database. RESTful is the most
common messaging protocol.
MySQL
MySQL.jl is the package to access MySQL from Julia programming language.
Use the following code to install the master version of MySQL API:
Pkg.clone("https://github.com/JuliaComputing/MySQL.jl")
Example
To access MySQL API, we need to first connect to the MySQL server which can be done
with the help of following code:
using MySQL
con = mysql_connect(HOST, USER, PASSWD, DBNAME)
To work with database, use the following code snippet to create a table:
JoinDate DATE,
LastLogin DATETIME,
LunchTime TIME,
PRIMARY KEY (ID)
);"""
response = mysql_query(con, command)
if (response == 0)
println("Create table succeeded.")
else
println("Create table failed.")
end
We can use the following command to obtain the SELECT query result as dataframe:
We can use the following command to obtain the SELECT query result as Julia Array:
We can use the following command to obtain the SELECT query result as Julia Array with
each row as a tuple:
stmt = mysql_stmt_init(con)
if (stmt == C_NULL)
error("Error in initialization of statement.")
197
Julia Programming
end
dframe = mysql_stmt_result_to_dataframe(stmt)
mysql_stmt_close(stmt)
mysql_disconnect(con)
JDBC
JDBC.jl is Julia interface to Java database drivers. The package JDBC.jl enables us the
use of Java JDBC drivers to access databases from within Julia programming language.
To start working with it, we need to first add the database driver jar file to the classpath
and then initialize the JVM as follows:
using JDBC
JavaCall.addClassPath("path of .jar file") # add the path of your .jar file
JDBC.init()
Example
The JDBC API in Julia is similar to Java JDBC driver. To connect with a database, we need
to follow similar steps as shown below:
conn = DriverManager.getConnection("jdbc:gl:test/juliatest")
stmt = createStatement(conn)
rs = executeQuery(stmt, "select * from mytable")
for r in rs
println(getInt(r, 1), getString(r,"NAME"))
end
198
Julia Programming
If you want to get each row as a Julia tuple, use JDBCRowIterator to iterate over the result
set. Note that if the values are declared to be nullable in the database, they will be of
nullable in tuples also.
for r in JDBCRowIterator(rs)
println(r)
end
Metadata
In order to get an array of (column_name, column_type) tuples, we need to Pass
the JResultSet object from executeQuery to getTableMetaData as follows:
conn = DriverManager.getConnection("jdbc:gl:test/juliatest")
stmt = createStatement(conn)
rs = executeQuery(stmt, "select * from mytable")
metadata = getTableMetaData(rs)
close(conn)
Executing a query
For executing a query, we need a cursor first. Once obtained a cursor you can run
execute! command on the cursor as follows:
199
Julia Programming
csr = cursor(conn)
execute!(csr, "insert into ptable (pvalue) values (3.14);")
execute!(csr, "select * from gltable;")
rs = rows(csr)
for row in rs
end
close(csr)
ODBC
ODBC.jl is a package which provides us a Julia ODBC API interface. It is implemented by
various ODBC driver managers. We can install it as follows:
julia> Pkg.add(“ODBC”)
We need to pass:
Enabling Connections
After installing the drivers, we can do the following for enabling connections:
200
Julia Programming
Executing Queries
Following are two paths to execute queries:
SQLite
SQLlite is a fast, flexible delimited file reader and writer for Julia programming language.
This package is registered in METADATA.jl hence can be installed by using the following
command:
julia> Pkg.add("SQLite")
We will discuss two important and useful functions used in SQLite along with the example:
Example
julia> db = SQLite.DB("Chinook_Sqlite.sqlite")
Here we are using a sample database ‘Chinook’ available for SQLite, SQL Server, MySQL,
etc.
Example
201
Julia Programming
| 6 | 25 | "Opera" |
PostgreSQL
PostgreSQL.jl is the PostgreSQL DBI driver. It is an interface to PostgreSQL from Julia
programming language. It obeys the DBI.jl protocol for working and uses the C
PostgreeSQL API (libpq).
using DBI
using PostgreSQL
end
finish(stmt)
disconnect(conn)
DBI.jl
DataFrames.jl >= v0.5.7
DataArrays.jl >= v0.1.2
libpq shared library (comes with a standard PostgreSQL client installation)
julia 0.3 or higher
Hive
Hive.jl is a client for distributed SQL engine. It provides a HiveServer2, for example: Hive,
Spark, SQL, Impala.
Connection
To connect to the server, we need to create an instance of the HiveSession as follows:
202
Julia Programming
session = HiveSession()
It can also be connected by specifying the hostname and the port number as follows:
session = HiveSession(“localhost”,10000)
The default implementation as above will authenticates with the same user-id as that of
the shell. We can override it as follows:
Other Packages
DBAPI is a new database interface proposal, inspired by Python’s DB API 2.0, that defies
an abstract interface for database drivers in Julia. This module contains the following:
Abstract types
Abstract required functions which throw a NotImplementedError by default
Abstract optional functions which throw a NotSupportedError by default
To use this API, the database drivers must import this module, subtype its types, and
create methods for its functions.
DBPrf is a Julia database which is maintained by JuliaDB. You see its usage below:
Command-Line mode
$ julia DBPerf.jl <Database_Driver_1.jl> <Database_Driver_2.jl> .......
<Database_Driver_N.jl> <DBMS>
ODBC.jl
JDBC.jl
203
Julia Programming
PostgreSQL.jl
MySQL.jl
Mongo.jl
SQLite.jl
Example
Example
204