- Mastering Julia
- Malcolm Sherrington
- 2480字
- 2021-07-16 13:42:38
Getting started
Starting to program in Julia is very easy. The first place to look at is the main Julia language website: http://julialang.org. This is not blotted with graphics, just the Julia logo, some useful major links to other parts of the site, and a quick sampler on the home page.
The Julia documentation is comprehensive of the docs link: http://docs.julialang.org. There are further links to the Julia manual, the standard library, and the package system, all of which we will be discussing later. Moreover, the documentation can be downloaded as a PDF file, a zipped file of HTML pages, or an ePub file.
Julia sources
At present, we will be looking at the download link. This provides links to 32-bit and 64-bit distros for Windows, Mac OS X, CentOS, and Ubuntu; both the stable release and the nightly development snapshot. So, a majority of the users getting started require nothing more than a download and a standard installation procedure.
For Windows, this is by running the downloaded .exe
file, which will extract Julia into a folder. Inside this folder is a batch file julia.bat
, which can be used to start the Julia console.
For Mac OS X, the users need to click on the downloaded .dmg
file to run the disk image and drag the app icon into the Applications
folder. On Mac OS X, you will be prompted to continue as the source has been downloaded from the Internet and so is not considered secure.
Similarly, uninstallation is a simple process. In Windows, delete the julia
folder, and in Mac OS X, delete Julia.app
. To do a "clean" uninstall, it is also necessary to tidy up a few hidden files/folders, and we will consider this after talking about the package system.
For Ubuntu (Linux), it's a little bit more involved as you need to add a reference to Personal Package Archive (PPA) to your system. You will have to have the root privilege for this to execute the following commands:
sudo apt-get add-repository ppa:staticfloat/juliareleases sudo add-apt-repository ppa:staticfloat/julia-deps sudo apt-get update sudo apt-get install julia
Tip
Downloading the example code
You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books that you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
The releases are provided by Elliot Saba, and there is a separate PPA for the nightly snapshots: ppa:staticfloat/julianightlies
.
It is only necessary to add PPA once, so for updates, all you need to do is execute the following command:
sudo apt-get update
Building from source
Ubuntu is part of the Debian family of Linux distributions, others being Debian itself, Linux Mint Debian Edition (LMDE), and Knoppix. All can install DEB packages and use the previous apt-get
command.
The other major Linux family is based on the Red Hat distribution: Red Hat Enterprise, CentOS, Fedora, Scientific Linux, and so on. These use a different package management mechanism based on RPM files. There are also distros based on SUSE, Mandriva, and Slackware.
For a comprehensive list, look at the Wikipedia page: http://en.wikipedia.org/wiki/List_of_Linux_distributions.
The link is again available from the julialang.org downloads page. Julia uses GitHub as a repository for its source distribution as well as for various Julia packages. We will look at installing on CentOS, which is the community edition of Red Hat and is widely used.
Installing on CentOS
CentOS can be downloaded as an ISO image from http://www.centos.org and written to a DVD. It can be installed as a replacement for an existing Windows system or to run alongside Windows as a dual-booted configuration.
CentOS does not come with the git
command as a standard; upon installation, the first task will be to install it. For this and other installation processes, we use the yum
command (Yellowdog Updater and Modified (YUM)).
You will need the root
/superuser
privileges, so typically, you would type su -
:
su – (type root password) yum update yum install git
Yum will fetch the Git sources for a Red Hat repository, list what needs to be installed, and prompt you to press Y
/N
to continue.
Once you have installed Git, we will need to grab the Julia sources from GitHub by using the following command:
git clone git://Github.com/JuliaLang/julia.git
(It is also possible to use https://
instead of git://
, if behind a firewall).
git clone git://Github.com/JuliaLang/julia.git Cloning into 'julia'... remote: Counting objects: 97173, done. remote: Compressing objects: 100% (24020/2
This will produce a subfolder at the current location called julia
with all the sources and documentation.
To build, Julia requires development tools that are not normally present in a standard CentOS distribution, particularly GCC, g++, and gfortran.
These can be installed as follows:
sudo yum install gcc sudo yum install gcc-c++ sudo yum install gcc-gfortran
Or, more conveniently, via a group install bundle:
sudo yum groupinstall 'Development tools'
Other tools (which are usually present) such as GNU Make, Perl, and patch are needed, but groupinstall
should take care of these too if not present. We did find that an installation on Fedora 19 failed because the M4 processor was not found, but again, yum install m4
was all that was required and the process could be resumed from where it failed.
So, to proceed with the build, we change into the cloned julia
folder and issue the make
command. Note that for seasoned Linux open source builders, there is no need for a configuration step. All the prerequisites are assumed to be in place (or else the make fails), and the executable is created in the julia
folder, so there is no make install
step.
The build process can take considerable time and produces a number of warnings on inpidual source files but when it has finished, it produces a file called julia
in the build folder. This is a symbolic link to the actual executable in the usr
/bin
folder.
So, typically, if all the tools are in place, the process may look like this:
[malcolm@localhost] cd ~ [malcolm@localhost] mkdir Build [malcolm@localhost] cd Build [malcolm@localhost Build] git clone git://github.com/JuliaLang/julia.git [malcolm@localhost julia] cd julia [malcolm@localhost julia] make After the build: [malcolm@localhost julia] ls -l julia lrwxrwxrwx 1 malcolm malcolm 39 Jun 10 09:11 julia -> /home/malcolm/Build/julia/usr/bin/julia
If you have (or create) a bin
folder just under the home
folder, it is worth recreating the link there as it will be automatically appended to the path.
[malcolm@localhost] cd ~/bin [malcolm@localhost bin] ln -s /home/malcolm/Build/julia/usr/bin/julia julia
To test out the installation (assuming julia
is on your path), use the following command:
[malcolm@localhost] julia -q
The -q
switch on the julia
command represses the print of the Julia banner.
julia> println("I've just installed Julia") I've just installed Julia
The julia>
prompt indicates the normal command mode. It is worth noting that there are a couple of other modes, which can be used at the console help (?
) and shell (;
).
For example:
julia>?print ?print Base.print(x) Write (to the default output stream) a canonical (un-decorated) text representation of a value if there is one, otherwise call "show". The representation used by "print" includes minimal formatting and tries to avoid Julia-specific details. julia> ;ls ;ls asian-ascplot.jl asian-winplot.jl asian.jl asian.m asian.o asian.r run-asian.jl time-asian.jl
We will be looking at an example of Julia code in the next section, but if you want to be a little more adventurous, try typing in the following at the julia>
prompt:
sumsq(x,y) = x^2 + y^2; N=1000000; x = 0; for i = 1:N if sumsq(rand(), rand()) < 1.0 x += 1; end end @printf "Estimate of PI for %d trials is %8.5f\n" N 4.0*(x / N);
- This is a simple estimate of PI by generating pairs of random numbers distributed uniformly over a unit square [
0.0:1.0, 0.0:1.0
]. If the sum of the squares of the pairs of numbers is less than1.0
, then the point defined by the two numbers lies within the unit circle. The ratio of the sum of all such points to the total number of pairs will be in the region of one quarter PI. - The line
sumsq(x,y) = x^2 + y^2
is an example of an inline function definition. Of course, multiline definitions are possible and more common but the use of one-liners is very convenient. It is possible to define anonymous functions too, as we will see later. - Although Julia is strictly typed, a variables type is inferred from the assignment unless explicitly defined.
- Constructs such as
for
loops andif
statements are terminated withend
, and there are no curly brackets{}
or matchingendfor
orendif
. Printing to the standard output can be done using theprintln
call, which is a function and needs the brackets.@printf
is an example of a macro that mimics the C-likeprintf
function allowing us to format outputted values.
Mac OS X and Windows
It is possible to download the stable build and the nightly release on Mac OS X, Windows, and Ubuntu. So, building Julia from source is less important than under distributions that do not provide a distro. However, since Julia is open source, it is possible to get detailed instructions from the Julia language website https://Github.com/JuliaLang/julia/blob/master/README.md.
On Mac OS X, you need to use a 64-bit gfortran compiler to build Julia. This can be downloaded from HPC - Mac OS X on SourceForge http://hpc.sourceforge.net. In order to work correctly, HPC gfortran requires HPC GCC to be installed as well. From OS X 10.7, Clang is now used by default to build Julia, and Xcode version 5 or later should be used. The minimum version of Clang needed to build Julia is v3.1.
Building under Windows is tricky and will not be covered here. It uses the Minimalist GNU for Windows (MinGW) distribution, and there are many caveats. If you wish to try it out, there is a comprehensive guide on the Julia site.
Exploring the source stack
Let's look at the top-level folders in the source tree that we get from GitHub:

To gain some insight into Julia coding, the best folders to look at are base
, examples
, and test
.
- The
base
folder contains a great portion of the standard library and the coding style exemplary. - The
test
folder has some code that illustrates how to write test scripts and use theBase.Test
system. - The
examples
folder gives Julia's take on some well-known old computing chestnuts such as Queens Problem, Wordcounts, and Game of Life.
If you have created Julia from source, you will have all the folders available in the Git/build folder; the build process creates a new folder tree in the folder starting with usr
and the executable is in the usr
/bin
folder.
Installing on a Mac under OS X creates Julia in /Applications
/Julia-[version].app
, where version
is the build number being installed. The executables required are in a subfolder of Contents
/Resources
/julia
/bin
. To find the Julia sources, look into the share
folder and go down one level in to the julia
subfolder.
So, the complete path will be similar to /Applications/julia-0.2.1.app/Contents/Resources/julia/share/julia
. This has the Julia files but not the C/C++ and Scheme files and so on; for these, you will need to checkout a source tree from GitHub.
For Windows, the situation is similar to that of Mac OS X. The installation file creates a folder called julia-[build-number]
where build-number
is typically an alpha string such as e44b593905
. Immediately under it are the bin
and share
folders (among others), and the share
folder contains a subfolder named julia
with the Julia scripts in it.
Juno
Juno is an IDE, which is bundled, for stable distributions on the Julia website. There are different versions for most popular operating systems.
It requires unzipping into a subfolder and putting the Juno executable on the run-search path, so it is one of the easiest ways to get started on a variety of platforms. It uses Light Table, so unlike IJulia (explained in the following section), it does not need a helper task (viz. Python) to be present.
The driver is the Jewel.jl
package, which is a collection of IDE-related code and is responsible for communication with Light Table. The IDE has a built-in workspace and navigator. Opening a folder in the workspace will display all the files via the navigator.
Juno handles things such as the following:
- Extensible autocomplete
- Pulling code blocks out of files at a given cursor position
- Finding relevant documentation or method definitions at the cursor
- Detecting the module to which a file belongs
- Evaluation of code blocks with the correct file, line, and module data
Juno's basic job is to transform expressions into values, which it does on pressing Ctrl + Enter, (Cmd + Enter on Mac OS X) inside a block. The code block is evaluated as a whole, rather than line by line, and the final result returned.
By default, the result is "collapsed." It is necessary to click on the bold text to toggle the content of the result. Graphs, from Winston and Gadfly, say, are displayed in line within Juno, not as a separate window.
IJulia
IJulia is a backend interface to the Julia language, which uses the IPython interactive environment. It is now part of Jupyter, a project to port the agnostic parts of IPython for use with other programming languages.
This combination allows you to interact with the Julia language by using IPython's powerful graphical notebook, which combines code, formatted text, math support, and multimedia in a single document.
You need version 1.0 or later of IPython. Note that IPython 1.0 was released in August 2013, so the version of Python required is 2.7 and the version pre-packaged with operating-system
distribution may be too old to run it. If so, you may have to install IPython manually.
On Mac OS X and Windows systems, the easiest way is to use the Anaconda Python installer. After installing Anaconda, use the conda
command to install IPython:
conda update conda conda update ipython
On Ubuntu, we use the apt-get
command and it's a good idea to install matplotlib
(for graphics) plus a cocktail of other useful modules.
sudo apt-get install python-matplotlib python-scipy python-pandas python-sympy python-nose
IPython is available on Fedora (v18+) but not yet on CentOS (v6.5) although this should be resolved with CentOS 7. Installation is via yum
as follows:
sudo yum install python-matplotlib scipy python-pandas sympy python-nose
The IPython notebook interface runs in your web browser and provides a rich multimedia environment. Furthermore, it is possible to produce some graphic output via Python's matplotlib
by using a Julia to Python interface. This requires installation of the IJulia package.
Start IJulia from the command line by typing ipython notebook --profile julia
, which opens a window in your browser.
This can be used as a console interface to Julia; using the PyPlot
package is also a convenient way to plot some curves.
The following screenshot displays a damped sinusoid of the form x*exp(-0.1x)*cos(2.0x)
:

- 深入理解Bootstrap
- Java系統分析與架構設計
- JMeter 性能測試實戰(第2版)
- 算法大爆炸:面試通關步步為營
- Mastering Articulate Storyline
- 從0到1:HTML+CSS快速上手
- Object-Oriented JavaScript(Second Edition)
- Swift 3 New Features
- Monitoring Elasticsearch
- Building Minecraft Server Modifications
- Learning YARN
- Principles of Strategic Data Science
- Go語言從入門到精通
- Instant Automapper
- Implementing Microsoft Dynamics NAV(Third Edition)