Julia Lang v0.4
Julia Lang v0.4
Julia Lang v0.4
Release 0.4.0-dev
Jeff Bezanson, Stefan Karpinski, Viral Shah, Alan Edelman, et al.
September 02, 2014
Contents
1 The Julia Manual 1
1.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.4 Integers and Floating-Point Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.5 Mathematical Operations and Elementary Functions . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.6 Complex and Rational Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
1.7 Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
1.8 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
1.9 Control Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
1.10 Scope of Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
1.11 Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
1.12 Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
1.13 Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
1.14 Conversion and Promotion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
1.15 Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
1.16 Metaprogramming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
1.17 Multi-dimensional Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
1.18 Linear algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
1.19 Networking and Streams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
1.20 Parallel Computing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
1.21 Interacting With Julia . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
1.22 Running External Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
1.23 Calling C and Fortran Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
1.24 Embedding Julia . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
1.25 Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
1.26 Package Development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
1.27 Performance Tips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
1.28 Style Guide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
1.29 Frequently Asked Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
1.30 Noteworthy Differences from other Languages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
2 The Julia Standard Library 201
2.1 The Standard Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
2.2 Sparse Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
2.3 Linear Algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
2.4 BLAS Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
2.5 Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292
i
2.6 Filesystem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292
2.7 Punctuation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
2.8 Sorting and Related Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
2.9 Package Manager Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
2.10 Collections and Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
2.11 Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
2.12 Unit and Functional Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
2.13 Testing Base Julia . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
2.14 Proling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
Bibliography 311
ii
CHAPTER 1
The Julia Manual
1.1 Introduction
Scientic computing has traditionally required the highest performance, yet domain experts have largely moved to
slower dynamic languages for daily work. We believe there are many good reasons to prefer dynamic languages
for these applications, and we do not expect their use to diminish. Fortunately, modern language design and compiler
techniques make it possible to mostly eliminate the performance trade-off and provide a single environment productive
enough for prototyping and efcient enough for deploying performance-intensive applications. The Julia programming
language lls this role: it is a exible dynamic language, appropriate for scientic and numerical computing, with
performance comparable to traditional statically-typed languages.
Because Julias compiler is different from the interpreters used for languages like Python or R, you may nd that
Julias performance is unintuitive at rst. If you nd that something is slow, we highly recommend reading through
the Performance Tips section before trying anything else. Once you understand how Julia works, its easy to write
code thats nearly as fast as C.
Julia features optional typing, multiple dispatch, and good performance, achieved using type inference and just-in-
time (JIT) compilation, implemented using LLVM. It is multi-paradigm, combining features of imperative, functional,
and object-oriented programming. Julia provides ease and expressiveness for high-level numerical computing, in the
same way as languages such as R, MATLAB, and Python, but also supports general programming. To achieve this,
Julia builds upon the lineage of mathematical programming languages, but also borrows much from popular dynamic
languages, including Lisp, Perl, Python, Lua, and Ruby.
The most signicant departures of Julia from typical dynamic languages are:
The core language imposes very little; the standard library is written in Julia itself, including primitive operations
like integer arithmetic
A rich language of types for constructing and describing objects, that can also optionally be used to make type
declarations
The ability to dene function behavior across many combinations of argument types via multiple dispatch
Automatic generation of efcient, specialized code for different argument types
Good performance, approaching that of statically-compiled languages like C
Although one sometimes speaks of dynamic languages as being typeless, they are denitely not: every object,
whether primitive or user-dened, has a type. The lack of type declarations in most dynamic languages, however,
means that one cannot instruct the compiler about the types of values, and often cannot explicitly talk about types at
all. In static languages, on the other hand, while one can and usually must annotate types for the compiler, types
exist only at compile time and cannot be manipulated or expressed at run time. In Julia, types are themselves run-time
objects, and can also be used to convey information to the compiler.
1
Julia Language Documentation, Release 0.4.0-dev
While the casual programmer need not explicitly use types or multiple dispatch, they are the core unifying features
of Julia: functions are dened on different combinations of argument types, and applied by dispatching to the most
specic matching denition. This model is a good t for mathematical programming, where it is unnatural for the rst
argument to own an operation as in traditional object-oriented dispatch. Operators are just functions with special
notation to extend addition to new user-dened data types, you dene new methods for the + function. Existing
code then seamlessly applies to the new data types.
Partly because of run-time type inference (augmented by optional type annotations), and partly because of a strong
focus on performance from the inception of the project, Julias computational efciency exceeds that of other dynamic
languages, and even rivals that of statically-compiled languages. For large scale numerical problems, speed always
has been, continues to be, and probably always will be crucial: the amount of data being processed has easily kept
pace with Moores Law over the past decades.
Julia aims to create an unprecedented combination of ease-of-use, power, and efciency in a single language. In
addition to the above, some advantages of Julia over comparable systems include:
Free and open source (MIT licensed)
User-dened types are as fast and compact as built-ins
No need to vectorize code for performance; devectorized code is fast
Designed for parallelism and distributed computation
Lightweight green threading (coroutines)
Unobtrusive yet powerful type system
Elegant and extensible conversions and promotions for numeric and other types
Efcient support for Unicode, including but not limited to UTF-8
Call C functions directly (no wrappers or special APIs needed)
Powerful shell-like capabilities for managing other processes
Lisp-like macros and other metaprogramming facilities
1.2 Getting Started
Julia installation is straightforward, whether using precompiled binaries or compiling from source. Download and
install Julia by following the instructions at http://julialang.org/downloads/.
The easiest way to learn and experiment with Julia is by starting an interactive session (also known as a read-eval-print
loop or repl):
$ julia
_
_ _ _(_)_ | A fresh approach to technical computing
(_) | (_) (_) | Documentation: http://docs.julialang.org
_ _ _| |_ __ _ | Type "help()" to list help topics
| | | | | | |/ _ | |
| | |_| | | | (_| | | Version 0.3.0-prerelease+3690 (2014-06-16 05:11 UTC)
_/ |\___|_|_|\___| | Commit 1b73f04
*
(0 days old master)
|__/ | x86_64-apple-darwin13.1.0
julia> 1 + 2
3
julia> ans
3
2 Chapter 1. The Julia Manual
Julia Language Documentation, Release 0.4.0-dev
To exit the interactive session, type ^D the control key together with the d key or type quit(). When run in
interactive mode, julia displays a banner and prompts the user for input. Once the user has entered a complete
expression, such as 1 + 2, and hits enter, the interactive session evaluates the expression and shows its value. If an
expression is entered into an interactive session with a trailing semicolon, its value is not shown. The variable ans
is bound to the value of the last evaluated expression whether it is shown or not. The ans variable is only bound in
interactive sessions, not when Julia code is run in other ways.
To evaluate expressions written in a source le file.jl, write include("file.jl").
To run code in a le non-interactively, you can give it as the rst argument to the julia command:
$ julia script.jl arg1 arg2...
As the example implies, the following command-line arguments to julia are taken as command-line arguments to the
program script.jl, passed in the global constant ARGS. ARGS is also set when script code is given using the -e
option on the command line (see the julia help output below). For example, to just print the arguments given to a
script, you could do this:
$ julia -e for x in ARGS; println(x); end foo bar
foo
bar
Or you could put that code into a script and run it:
$ echo for x in ARGS; println(x); end > script.jl
$ julia script.jl foo bar
foo
bar
Julia can be started in parallel mode with either the -p or the --machinefile options. -p n will launch an
additional n worker processes, while --machinefile file will launch a worker for each line in le file. The
machines dened in file must be accessible via a passwordless ssh login, with Julia installed at the same location as
the current host. Each machine denition takes the form[user@]host[:port] [bind_addr] . user defaults
to current user, port to the standard ssh port. Optionally, in case of multi-homed hosts, bind_addr may be used to
explicitly specify an interface.
If you have code that you want executed whenever julia is run, you can put it in ~\.juliarc.jl:
$ echo println("Greetings! ! ?") > ~/.juliarc.jl
$ julia
Greetings! ! ?
...
There are various ways to run Julia code and provide options, similar to those available for the perl and ruby
programs:
julia [options] [program] [args...]
-v, --version Display version information
-h, --help Print this message
-q, --quiet Quiet startup without banner
-H, --home <dir> Set location of julia executable
-e, --eval <expr> Evaluate <expr>
-E, --print <expr> Evaluate and show <expr>
-P, --post-boot <expr> Evaluate <expr> right after boot
-L, --load <file> Load <file> right after boot on all processors
-J, --sysimage <file> Start up with the given system image file
-p <n> Run n local processes
1.2. Getting Started 3
Julia Language Documentation, Release 0.4.0-dev
--machinefile <file> Run processes on hosts listed in <file>
-i Force isinteractive() to be true
--no-history-file Dont load or save history
-f, --no-startup Dont load ~/.juliarc.jl
-F Load ~/.juliarc.jl, then handle remaining inputs
--color={yes|no} Enable or disable color text
--code-coverage Count executions of source lines
--check-bounds={yes|no} Emit bounds checks always or never (ignoring declarations)
--int-literals={32|64} Select integer literal size independent of platform
1.2.1 Resources
In addition to this manual, there are various other resources that may help new users get started with julia:
Julia and IJulia cheatsheet
Learn Julia in a few minutes
Tutorial for Homer Reids numerical analysis class
An introductory presentation
Videos from the Julia tutorial at MIT
Forio Julia Tutorials
1.3 Variables
A variable, in Julia, is a name associated (or bound) to a value. Its useful when you want to store a value (that you
obtained after some math, for example) for later use. For example:
# Assign the value 10 to the variable x
julia> x = 10
10
# Doing math with xs value
julia> x + 1
11
# Reassign xs value
julia> x = 1 + 1
2
# You can assign values of other types, like strings of text
julia> x = "Hello World!"
"Hello World!"
Julia provides an extremely exible system for naming variables. Variable names are case-sensitive, and have no
semantic meaning (that is, the language will not treat variables differently based on their names).
julia> x = 1.0
1.0
julia> y = -3
-3
4 Chapter 1. The Julia Manual
Julia Language Documentation, Release 0.4.0-dev
julia> Z = "My string"
"My string"
julia> customary_phrase = "Hello world!"
"Hello world!"
julia> UniversalDeclarationOfHumanRightsStart = ""
""
Unicode names (in UTF-8 encoding) are allowed:
julia> = 0.00001
1.0e-5
julia> = "Hello"
"Hello"
In the Julia REPL and several other Julia editing environments, you can type many Unicode math symbols by typing
the backslashed LaTeX symbol name followed by tab. For example, the variable name can be entered by typing
\delta-tab, or even 2 by \alpha-tab-\hat-tab-\_2-tab. Julia will even let you redene built-in constants and
functions if needed:
julia> pi
= 3.1415926535897...
julia> pi = 3
Warning: imported binding for pi overwritten in module Main
3
julia> pi
3
julia> sqrt(100)
10.0
julia> sqrt = 4
Warning: imported binding for sqrt overwritten in module Main
4
However, this is obviously not recommended to avoid potential confusion.
1.3.1 Allowed Variable Names
Variable names must begin with a letter (A-Z or a-z), underscore, or a subset of Unicode code points greater than
00A0; in particular, Unicode character categories Lu/Ll/Lt/Lm/Lo/Nl (letters), Sc/So (currency and other symbols),
and a few other letter-like characters (e.g. a subset of the Sm math symbols) are allowed. Subsequent characters
may also include ! and digits (0-9 and other characters in categories Nd/No), as well as other Unicode code points:
diacritics and other modifying marks (categories Mn/Mc/Me/Sk), some punctuation connectors (category Pc), primes,
and a few other characters.
Operators like + are also valid identiers, but are parsed specially. In some contexts, operators can be used just like
variables; for example (+) refers to the addition function, and (+) = f will reassign it. Most of the Unicode inx
operators (in category Sm), such as , are parsed as inx operators and are available for user-dened methods (e.g.
you can use const = kron to dene as an inx Kronecker product).
The only explicitly disallowed names for variables are the names of built-in statements:
1.3. Variables 5
Julia Language Documentation, Release 0.4.0-dev
julia> else = false
ERROR: syntax: unexpected "else"
julia> try = "No"
ERROR: syntax: unexpected "="
1.3.2 Stylistic Conventions
While Julia imposes few restrictions on valid names, it has become useful to adopt the following conventions:
Names of variables are in lower case.
Word separation can be indicated by underscores (_), but use of underscores is discouraged unless the name
would be hard to read otherwise.
Names of Types begin with a capital letter and word separation is shown with CamelCase instead of under-
scores.
Names of functions and macros are in lower case, without underscores.
Functions that modify their inputs have names that end in !. These functions are sometimes called mutating
functions or in-place functions.
1.4 Integers and Floating-Point Numbers
Integers and oating-point values are the basic building blocks of arithmetic and computation. Built-in representations
of such values are called numeric primitives, while representations of integers and oating-point numbers as immediate
values in code are known as numeric literals. For example, 1 is an integer literal, while 1.0 is a oating-point literal;
their binary in-memory representations as objects are numeric primitives.
Julia provides a broad range of primitive numeric types, and a full complement of arithmetic and bitwise operators as
well as standard mathematical functions are dened over them. These map directly onto numeric types and operations
that are natively supported on modern computers, thus allowing Julia to take full advantage of computational resources.
Additionally, Julia provides software support for Arbitrary Precision Arithmetic, which can handle operations on
numeric values that cannot be represented effectively in native hardware representations, but at the cost of relatively
slower performance.
The following are Julias primitive numeric types:
Integer types:
Type Signed? Number of bits Smallest value Largest value
Int8 x 8 -2^7 2^7 - 1
Uint8 8 0 2^8 - 1
Int16 x 16 -2^15 2^15 - 1
Uint16 16 0 2^16 - 1
Int32 x 32 -2^31 2^31 - 1
Uint32 32 0 2^32 - 1
Int64 x 64 -2^63 2^63 - 1
Uint64 64 0 2^64 - 1
Int128 x 128 -2^127 2^127 - 1
Uint128 128 0 2^128 - 1
Bool N/A 8 false (0) true (1)
Char N/A 32 \0 \Uffffffff
Char natively supports representation of Unicode characters; see Strings for more details.
6 Chapter 1. The Julia Manual
Julia Language Documentation, Release 0.4.0-dev
Floating-point types:
Type Precision Number of bits
Float16 half 16
Float32 single 32
Float64 double 64
Additionally, full support for Complex and Rational Numbers is built on top of these primitive numeric types. All
numeric types interoperate naturally without explicit casting, thanks to a exible, user-extensible type promotion
system.
1.4.1 Integers
Literal integers are represented in the standard manner:
julia> 1
1
julia> 1234
1234
The default type for an integer literal depends on whether the target system has a 32-bit architecture or a 64-bit
architecture:
# 32-bit system:
julia> typeof(1)
Int32
# 64-bit system:
julia> typeof(1)
Int64
The Julia internal variable WORD_SIZE indicates whether the target system is 32-bit or 64-bit.:
# 32-bit system:
julia> WORD_SIZE
32
# 64-bit system:
julia> WORD_SIZE
64
Julia also denes the types Int and Uint, which are aliases for the systems signed and unsigned native integer types
respectively.:
# 32-bit system:
julia> Int
Int32
julia> Uint
Uint32
# 64-bit system:
julia> Int
Int64
julia> Uint
Uint64
1.4. Integers and Floating-Point Numbers 7
Julia Language Documentation, Release 0.4.0-dev
Larger integer literals that cannot be represented using only 32 bits but can be represented in 64 bits always create
64-bit integers, regardless of the system type:
# 32-bit or 64-bit system:
julia> typeof(3000000000)
Int64
Unsigned integers are input and output using the 0x prex and hexadecimal (base 16) digits 0-9a-f (the capitalized
digits A-F also work for input). The size of the unsigned value is determined by the number of hex digits used:
julia> 0x1
0x01
julia> typeof(ans)
Uint8
julia> 0x123
0x0123
julia> typeof(ans)
Uint16
julia> 0x1234567
0x01234567
julia> typeof(ans)
Uint32
julia> 0x123456789abcdef
0x0123456789abcdef
julia> typeof(ans)
Uint64
This behavior is based on the observation that when one uses unsigned hex literals for integer values, one typically is
using them to represent a xed numeric byte sequence, rather than just an integer value.
Recall that the variable ans is set to the value of the last expression evaluated in an interactive session. This does not
occur when Julia code is run in other ways.
Binary and octal literals are also supported:
julia> 0b10
0x02
julia> typeof(ans)
Uint8
julia> 0o10
0x08
julia> typeof(ans)
Uint8
The minimum and maximum representable values of primitive numeric types such as integers are given by the
typemin and typemax functions:
julia> (typemin(Int32), typemax(Int32))
(-2147483648,2147483647)
8 Chapter 1. The Julia Manual
Julia Language Documentation, Release 0.4.0-dev
julia> for T = {Int8,Int16,Int32,Int64,Int128,Uint8,Uint16,Uint32,Uint64,Uint128}
println("$(lpad(T,7)): [$(typemin(T)),$(typemax(T))]")
end
Int8: [-128,127]
Int16: [-32768,32767]
Int32: [-2147483648,2147483647]
Int64: [-9223372036854775808,9223372036854775807]
Int128: [-170141183460469231731687303715884105728,170141183460469231731687303715884105727]
Uint8: [0,255]
Uint16: [0,65535]
Uint32: [0,4294967295]
Uint64: [0,18446744073709551615]
Uint128: [0,340282366920938463463374607431768211455]
The values returned by typemin and typemax are always of the given argument type. (The above expression uses
several features we have yet to introduce, including for loops, Strings, and Interpolation, but should be easy enough
to understand for users with some existing programming experience.)
Overow behavior
In Julia, exceeding the maximum representable value of a given type results in a wraparound behavior:
julia> x = typemax(Int64)
9223372036854775807
julia> x + 1
-9223372036854775808
julia> x + 1 == typemin(Int64)
true
Thus, arithmetic with Julia integers is actually a form of modular arithmetic. This reects the characteristics of the
underlying arithmetic of integers as implemented on modern computers. In applications where overow is possi-
ble, explicit checking for wraparound produced by overow is essential; otherwise, the BigInt type in Arbitrary
Precision Arithmetic is recommended instead.
To minimize the practical impact of this overow, integer addition, subtraction, multiplication, and exponentiation
operands are promoted to Int or Uint from narrower integer types. (However, divisions, remainders, and bitwise
operations do not promote narrower types.)
Division errors
Integer division (the div function) has two exceptional cases: dividing by zero, and dividing the lowest negative
number (typemin) by -1. Both of these cases throw a DivideError. The remainder and modulus functions (rem
and mod) throw a DivideError when their second argument is zero.
1.4.2 Floating-Point Numbers
Literal oating-point numbers are represented in the standard formats:
julia> 1.0
1.0
julia> 1.
1.0
1.4. Integers and Floating-Point Numbers 9
Julia Language Documentation, Release 0.4.0-dev
julia> 0.5
0.5
julia> .5
0.5
julia> -1.23
-1.23
julia> 1e10
1.0e10
julia> 2.5e-4
0.00025
The above results are all Float64 values. Literal Float32 values can be entered by writing an f in place of e:
julia> 0.5f0
0.5f0
julia> typeof(ans)
Float32
julia> 2.5f-4
0.00025f0
Values can be converted to Float32 easily:
julia> float32(-1.5)
-1.5f0
julia> typeof(ans)
Float32
Hexadecimal oating-point literals are also valid, but only as Float64 values:
julia> 0x1p0
1.0
julia> 0x1.8p3
12.0
julia> 0x.4p-1
0.125
julia> typeof(ans)
Float64
Half-precision oating-point numbers are also supported (Float16), but only as a storage format. In calculations
theyll be converted to Float32:
julia> sizeof(float16(4.))
2
julia> 2
*
float16(4.)
8.0f0
10 Chapter 1. The Julia Manual
Julia Language Documentation, Release 0.4.0-dev
Floating-point zero
Floating-point numbers have two zeros, positive zero and negative zero. They are equal to each other but have different
binary representations, as can be seen using the bits function: :
julia> 0.0 == -0.0
true
julia> bits(0.0)
"0000000000000000000000000000000000000000000000000000000000000000"
julia> bits(-0.0)
"1000000000000000000000000000000000000000000000000000000000000000"
Special oating-point values
There are three specied standard oating-point values that do not correspond to any point on the real number line:
Special value Name Description
Float16 Float32 Float64
Inf16 Inf32 Inf positive
innity
a value greater than all nite oating-point values
-Inf16 -Inf32 -Inf negative
innity
a value less than all nite oating-point values
NaN16 NaN32 NaN not a number a value not == to any oating-point value (including
itself)
For further discussion of how these non-nite oating-point values are ordered with respect to each other and other
oats, see Numeric Comparisons. By the IEEE 754 standard, these oating-point values are the results of certain
arithmetic operations:
julia> 1/Inf
0.0
julia> 1/0
Inf
julia> -5/0
-Inf
julia> 0.000001/0
Inf
julia> 0/0
NaN
julia> 500 + Inf
Inf
julia> 500 - Inf
-Inf
julia> Inf + Inf
Inf
julia> Inf - Inf
NaN
1.4. Integers and Floating-Point Numbers 11
Julia Language Documentation, Release 0.4.0-dev
julia> Inf
*
Inf
Inf
julia> Inf / Inf
NaN
julia> 0
*
Inf
NaN
The typemin and typemax functions also apply to oating-point types:
julia> (typemin(Float16),typemax(Float16))
(-Inf16,Inf16)
julia> (typemin(Float32),typemax(Float32))
(-Inf32,Inf32)
julia> (typemin(Float64),typemax(Float64))
(-Inf,Inf)
Machine epsilon
Most real numbers cannot be represented exactly with oating-point numbers, and so for many purposes it is important
to know the distance between two adjacent representable oating-point numbers, which is often known as machine
epsilon.
Julia provides the eps function, which gives the distance between 1.0 and the next larger representable oating-point
value:
julia> eps(Float32)
1.1920929f-7
julia> eps(Float64)
2.220446049250313e-16
julia> eps() # same as eps(Float64)
2.220446049250313e-16
These values are 2.0^-23 and 2.0^-52 as Float32 and Float64 values, respectively. The eps function can
also take a oating-point value as an argument, and gives the absolute difference between that value and the next
representable oating point value. That is, eps(x) yields a value of the same type as x such that x + eps(x) is
the next representable oating-point value larger than x:
julia> eps(1.0)
2.220446049250313e-16
julia> eps(1000.)
1.1368683772161603e-13
julia> eps(1e-27)
1.793662034335766e-43
julia> eps(0.0)
5.0e-324
The distance between two adjacent representable oating-point numbers is not constant, but is smaller for smaller
values and larger for larger values. In other words, the representable oating-point numbers are densest in the real
12 Chapter 1. The Julia Manual
Julia Language Documentation, Release 0.4.0-dev
number line near zero, and growsparser exponentially as one moves farther away fromzero. By denition, eps(1.0)
is the same as eps(Float64) since 1.0 is a 64-bit oating-point value.
Julia also provides the nextfloat and prevfloat functions which return the next largest or smallest representable
oating-point number to the argument respectively: :
julia> x = 1.25f0
1.25f0
julia> nextfloat(x)
1.2500001f0
julia> prevfloat(x)
1.2499999f0
julia> bits(prevfloat(x))
"00111111100111111111111111111111"
julia> bits(x)
"00111111101000000000000000000000"
julia> bits(nextfloat(x))
"00111111101000000000000000000001"
This example highlights the general principle that the adjacent representable oating-point numbers also have adjacent
binary integer representations.
Rounding modes
If a number doesnt have an exact oating-point representation, it must be rounded to an appropriate representable
value, however, if wanted, the manner in which this rounding is done can be changed according to the rounding modes
presented in the IEEE 754 standard:
julia> 1.1 + 0.1
1.2000000000000002
julia> with_rounding(Float64,RoundDown) do
1.1 + 0.1
end
1.2
The default mode used is always RoundNearest, which rounds to the nearest representable value, with ties rounded
towards the nearest value with an even least signicant bit.
Background and References
Floating-point arithmetic entails many subtleties which can be surprising to users who are unfamiliar with the low-
level implementation details. However, these subtleties are described in detail in most books on scientic computation,
and also in the following references:
The denitive guide to oating point arithmetic is the IEEE 754-2008 Standard; however, it is not available for
free online.
For a brief but lucid presentation of how oating-point numbers are represented, see John D. Cooks article
on the subject as well as his introduction to some of the issues arising from how this representation differs in
behavior from the idealized abstraction of real numbers.
Also recommended is Bruce Dawsons series of blog posts on oating-point numbers.
1.4. Integers and Floating-Point Numbers 13
Julia Language Documentation, Release 0.4.0-dev
For an excellent, in-depth discussion of oating-point numbers and issues of numerical accuracy encountered
when computing with them, see David Goldbergs paper What Every Computer Scientist Should Know About
Floating-Point Arithmetic.
For even more extensive documentation of the history of, rationale for, and issues with oating-point numbers,
as well as discussion of many other topics in numerical computing, see the collected writings of William Kahan,
commonly known as the Father of Floating-Point. Of particular interest may be An Interview with the Old
Man of Floating-Point.
1.4.3 Arbitrary Precision Arithmetic
To allow computations with arbitrary-precision integers and oating point numbers, Julia wraps the GNU Multiple
Precision Arithmetic Library (GMP) and the GNU MPFR Library, respectively. The BigInt and BigFloat types are
available in Julia for arbitrary precision integer and oating point numbers respectively.
Constructors exist to create these types from primitive numerical types, or from String. Once created, they partici-
pate in arithmetic with all other numeric types thanks to Julias type promotion and conversion mechanism. :
julia> BigInt(typemax(Int64)) + 1
9223372036854775808
julia> BigInt("123456789012345678901234567890") + 1
123456789012345678901234567891
julia> BigFloat("1.23456789012345678901")
1.234567890123456789010000000000000000000000000000000000000000000000000000000004e+00 with 256 bits of precision
julia> BigFloat(2.0^66) / 3
2.459565876494606882133333333333333333333333333333333333333333333333333333333344e+19 with 256 bits of precision
julia> factorial(BigInt(40))
815915283247897734345611269596115894272000000000
However, type promotion between the primitive types above and BigInt/BigFloat is not automatic and must be explic-
itly stated. :
julia> x = typemin(Int64)
-9223372036854775808
julia> x = x - 1
9223372036854775807
julia> typeof(x)
Int64
julia> y = BigInt(typemin(Int64))
-9223372036854775808
julia> y = y - 1
-9223372036854775809
julia> typeof(y)
BigInt (constructor with 10 methods)
The default precision (in number of bits of the signicand) and rounding mode of BigFloat operations can be changed,
and all further calculations will take these changes in account:
14 Chapter 1. The Julia Manual
Julia Language Documentation, Release 0.4.0-dev
julia> with_rounding(BigFloat,RoundUp) do
BigFloat(1) + BigFloat("0.1")
end
1.100000000000000000000000000000000000000000000000000000000000000000000000000003e+00 with 256 bits of precision
julia> with_rounding(BigFloat,RoundDown) do
BigFloat(1) + BigFloat("0.1")
end
1.099999999999999999999999999999999999999999999999999999999999999999999999999986e+00 with 256 bits of precision
julia> with_bigfloat_precision(40) do
BigFloat(1) + BigFloat("0.1")
end
1.1000000000004e+00 with 40 bits of precision
1.4.4 Numeric Literal Coefcients
To make common numeric formulas and expressions clearer, Julia allows variables to be immediately preceded by a
numeric literal, implying multiplication. This makes writing polynomial expressions much cleaner:
julia> x = 3
3
julia> 2x^2 - 3x + 1
10
julia> 1.5x^2 - .5x + 1
13.0
It also makes writing exponential functions more elegant:
julia> 2^2x
64
The precedence of numeric literal coefcients is the same as that of unary operators such as negation. So 2^3x is
parsed as 2^(3x), and 2x^3 is parsed as 2
*
(x^3).
Numeric literals also work as coefcients to parenthesized expressions:
julia> 2(x-1)^2 - 3(x-1) + 1
3
Additionally, parenthesized expressions can be used as coefcients to variables, implying multiplication of the expres-
sion by the variable:
julia> (x-1)x
6
Neither juxtaposition of two parenthesized expressions, nor placing a variable before a parenthesized expression,
however, can be used to imply multiplication:
julia> (x-1)(x+1)
ERROR: type: apply: expected Function, got Int64
julia> x(x+1)
ERROR: type: apply: expected Function, got Int64
1.4. Integers and Floating-Point Numbers 15
Julia Language Documentation, Release 0.4.0-dev
Both of these expressions are interpreted as function application: any expression that is not a numeric literal, when
immediately followed by a parenthetical, is interpreted as a function applied to the values in parentheses (see Functions
for more about functions). Thus, in both of these cases, an error occurs since the left-hand value is not a function.
The above syntactic enhancements signicantly reduce the visual noise incurred when writing common mathematical
formulae. Note that no whitespace may come between a numeric literal coefcient and the identier or parenthesized
expression which it multiplies.
Syntax Conicts
Juxtaposed literal coefcient syntax may conict with two numeric literal syntaxes: hexadecimal integer literals and
engineering notation for oating-point literals. Here are some situations where syntactic conicts arise:
The hexadecimal integer literal expression 0xff could be interpreted as the numeric literal 0 multiplied by the
variable xff.
The oating-point literal expression 1e10 could be interpreted as the numeric literal 1 multiplied by the variable
e10, and similarly with the equivalent E form.
In both cases, we resolve the ambiguity in favor of interpretation as a numeric literals:
Expressions starting with 0x are always hexadecimal literals.
Expressions starting with a numeric literal followed by e or E are always oating-point literals.
1.4.5 Literal zero and one
Julia provides functions which return literal 0 and 1 corresponding to a specied type or the type of a given variable.
Function Description
zero(x) Literal zero of type x or type of variable x
one(x) Literal one of type x or type of variable x
These functions are useful in Numeric Comparisons to avoid overhead from unnecessary type conversion.
Examples:
julia> zero(Float32)
0.0f0
julia> zero(1.0)
0.0
julia> one(Int32)
1
julia> one(BigFloat)
1e+00 with 256 bits of precision
1.5 Mathematical Operations and Elementary Functions
Julia provides a complete collection of basic arithmetic and bitwise operators across all of its numeric primitive types,
as well as providing portable, efcient implementations of a comprehensive collection of standard mathematical func-
tions.
16 Chapter 1. The Julia Manual
Julia Language Documentation, Release 0.4.0-dev
1.5.1 Arithmetic Operators
The following arithmetic operators are supported on all primitive numeric types:
Expression Name Description
+x unary plus the identity operation
-x unary minus maps values to their additive inverses
x + y binary plus performs addition
x - y binary minus performs subtraction
x
*
y times performs multiplication
x / y divide performs division
x \ y inverse divide equivalent to y / x
x ^ y power raises x to the yth power
x % y remainder equivalent to rem(x,y)
as well as the negation on Bool types:
Expression Name Description
!x negation changes true to false and vice versa
Julias promotion system makes arithmetic operations on mixtures of argument types just work naturally and auto-
matically. See Conversion and Promotion for details of the promotion system.
Here are some simple examples using arithmetic operators:
julia> 1 + 2 + 3
6
julia> 1 - 2
-1
julia> 3
*
2/12
0.5
(By convention, we tend to space less tightly binding operators less tightly, but there are no syntactic constraints.)
1.5.2 Bitwise Operators
The following bitwise operators are supported on all primitive integer types:
Expression Name
~x bitwise not
x & y bitwise and
x | y bitwise or
x $ y bitwise xor (exclusive or)
x >>> y logical shift right
x >> y arithmetic shift right
x << y logical/arithmetic shift left
Here are some examples with bitwise operators:
julia> ~123
-124
julia> 123 & 234
106
julia> 123 | 234
251
1.5. Mathematical Operations and Elementary Functions 17
Julia Language Documentation, Release 0.4.0-dev
julia> 123 $ 234
145
julia> ~uint32(123)
0xffffff84
julia> ~uint8(123)
0x84
1.5.3 Updating operators
Every binary arithmetic and bitwise operator also has an updating version that assigns the result of the operation back
into its left operand. The updating version of the binary operator is formed by placing a = immediately after the
operator. For example, writing x += 3 is equivalent to writing x = x + 3:
julia> x = 1
1
julia> x += 3
4
julia> x
4
The updating versions of all the binary arithmetic and bitwise operators are:
+= -=
*
= /= \= %= ^= &= |= $= >>>= >>= <<=
1.5.4 Numeric Comparisons
Standard comparison operations are dened for all the primitive numeric types:
Operator Name
== equality
!= = inequality
< less than
<= less than or equal to
> greater than
>= greater than or equal to
Here are some simple examples:
julia> 1 == 1
true
julia> 1 == 2
false
julia> 1 != 2
true
julia> 1 == 1.0
true
julia> 1 < 2
18 Chapter 1. The Julia Manual
Julia Language Documentation, Release 0.4.0-dev
true
julia> 1.0 > 3
false
julia> 1 >= 1.0
true
julia> -1 <= 1
true
julia> -1 <= -1
true
julia> -1 <= -2
false
julia> 3 < -0.5
false
Integers are compared in the standard manner by comparison of bits. Floating-point numbers are compared accord-
ing to the IEEE 754 standard:
Finite numbers are ordered in the usual manner.
Positive zero is equal but not greater than negative zero.
Inf is equal to itself and greater than everything else except NaN.
-Inf is equal to itself and less then everything else except NaN.
NaN is not equal to, not less than, and not greater than anything, including itself.
The last point is potentially surprising and thus worth noting:
julia> NaN == NaN
false
julia> NaN != NaN
true
julia> NaN < NaN
false
julia> NaN > NaN
false
and can cause especial headaches with Arrays:
julia> [1 NaN] == [1 NaN]
false
Julia provides additional functions to test numbers for special values, which can be useful in situations like hash key
comparisons:
Function Tests if
isequal(x, y) x and y are identical
isfinite(x) x is a nite number
isinf(x) x is innite
isnan(x) x is not a number
isequal considers NaNs equal to each other:
1.5. Mathematical Operations and Elementary Functions 19
Julia Language Documentation, Release 0.4.0-dev
julia> isequal(NaN,NaN)
true
julia> isequal([1 NaN], [1 NaN])
true
julia> isequal(NaN,NaN32)
true
isequal can also be used to distinguish signed zeros:
julia> -0.0 == 0.0
true
julia> isequal(-0.0, 0.0)
false
Mixed-type comparisons between signed integers, unsigned integers, and oats can be tricky. A great deal of care has
been taken to ensure that Julia does them correctly.
Chaining comparisons
Unlike most languages, with the notable exception of Python, comparisons can be arbitrarily chained:
julia> 1 < 2 <= 2 < 3 == 3 > 2 >= 1 == 1 < 3 != 5
true
Chaining comparisons is often quite convenient in numerical code. Chained comparisons use the && operator for scalar
comparisons, and the & operator for elementwise comparisons, which allows them to work on arrays. For example, 0
.< A .< 1 gives a boolean array whose entries are true where the corresponding elements of A are between 0 and
1.
The operator .< is intended for array objects; the operation A .< B is valid only if A and B have the same dimensions.
The operator returns an array with boolean entries and with the same dimensions as A and B. Such operators are called
elementwise; Julia offers a suite of elementwise operators: .
*
, .+, etc. Some of the elementwise operators can take a
scalar operand such as the example 0 .< A .< 1 in the preceding paragraph. This notation means that the scalar
operand should be replicated for each entry of the array.
Note the evaluation behavior of chained comparisons:
v(x) = (println(x); x)
julia> v(1) < v(2) <= v(3)
2
1
3
true
julia> v(1) > v(2) <= v(3)
2
1
false
The middle expression is only evaluated once, rather than twice as it would be if the expression were written as
v(1) < v(2) && v(2) <= v(3). However, the order of evaluations in a chained comparison is undened. It
is strongly recommended not to use expressions with side effects (such as printing) in chained comparisons. If side
effects are required, the short-circuit && operator should be used explicitly (see Short-Circuit Evaluation).
20 Chapter 1. The Julia Manual
Julia Language Documentation, Release 0.4.0-dev
Operator Precedence
Julia applies the following order of operations, from highest precedence to lowest:
Category Operators
Syntax . followed by ::
Exponenti-
ation
^ and its elementwise equivalent .^
Fractions // and .//
Multiplica-
tion
*
/ % & \ and .
*
./ .% .\
Bitshifts << >> >>> and .<< .>> .>>>
Addition + - | $ and .+ .-
Syntax : .. followed by |>
Compar-
isons
> < >= <= == === != !== <: and .> .< .>= .<= .== .!=
Control
ow
&& followed by || followed by ?
Assign-
ments
= += -=
*
= /= //= \= ^= %= |= &= $= <<= >>= >>>= and .+= .-= .
*
=
./= .//= .\= .^= .%=
1.5.5 Elementary Functions
Julia provides a comprehensive collection of mathematical functions and operators. These mathematical operations
are dened over as broad a class of numerical values as permit sensible denitions, including integers, oating-point
numbers, rationals, and complexes, wherever such denitions make sense.
Rounding functions
Function Description Return type
round(x) round x to the nearest integer FloatingPoint
iround(x) round x to the nearest integer Integer
floor(x) round x towards -Inf FloatingPoint
ifloor(x) round x towards -Inf Integer
ceil(x) round x towards +Inf FloatingPoint
iceil(x) round x towards +Inf Integer
trunc(x) round x towards zero FloatingPoint
itrunc(x) round x towards zero Integer
Division functions
Function Description
div(x,y) truncated division; quotient rounded towards zero
fld(x,y) oored division; quotient rounded towards -Inf
rem(x,y) remainder; satises x == div(x,y)
*
y + rem(x,y); sign matches x
divrem(x,y) returns (div(x,y),rem(x,y))
mod(x,y) modulus; satises x == fld(x,y)
*
y + mod(x,y); sign matches y
mod2pi(x) modulus with respect to 2pi; 0 <= mod2pi(x) < 2pi
gcd(x,y...) greatest common divisor of x, y,...; sign matches x
lcm(x,y...) least common multiple of x, y,...; sign matches x
1.5. Mathematical Operations and Elementary Functions 21
Julia Language Documentation, Release 0.4.0-dev
Sign and absolute value functions
Function Description
abs(x) a positive value with the magnitude of x
abs2(x) the squared magnitude of x
sign(x) indicates the sign of x, returning -1, 0, or +1
signbit(x) indicates whether the sign bit is on (1) or off (0)
copysign(x,y) a value with the magnitude of x and the sign of y
flipsign(x,y) a value with the magnitude of x and the sign of x
*
y
Powers, logs and roots
Function Description
sqrt(x)
julia> s[2]
ERROR: invalid UTF-8 character index
in next at ./utf8.jl:68
in getindex at string.jl:57
julia> s[3]
ERROR: invalid UTF-8 character index
in next at ./utf8.jl:68
in getindex at string.jl:57
julia> s[4]
In this case, the character is a three-byte character, so the indices 2 and 3 are invalid and the next characters index
is 4.
Because of variable-length encodings, the number of characters in a string (given by length(s)) is not always the
same as the last index. If you iterate through the indices 1 through endof(s) and index into s, the sequence of
characters returned when errors arent thrown is the sequence of characters comprising the string s. Thus we have the
identity that length(s) <= endof(s), since each character in a string must have its own index. The following
is an inefcient and verbose way to iterate through the characters of s:
julia> for i = 1:endof(s)
try
println(s[i])
catch
# ignore the index error
end
end
y
The blank lines actually have spaces on them. Fortunately, the above awkward idiom is unnecessary for iterating
through the characters in a string, since you can just use the string as an iterable object, no exception handling required:
julia> for c in s
println(c)
end
1.7. Strings 33
Julia Language Documentation, Release 0.4.0-dev
y
UTF-8 is not the only encoding that Julia supports, and adding support for new encodings is quite easy. In particu-
lar, Julia also provides UTF16String and UTF32String types, constructed by the utf16(s) and utf32(s)
functions respectively, for UTF-16 and UTF-32 encodings. It also provides aliases WString and wstring(s) for
either UTF-16 or UTF-32 strings, depending on the size of Cwchar_t. Additional discussion of other encodings and
how to implement support for them is beyond the scope of this document for the time being. For further discussion of
UTF-8 encoding issues, see the section below on byte array literals, which goes into some greater detail.
1.7.4 Interpolation
One of the most common and useful string operations is concatenation:
julia> greet = "Hello"
"Hello"
julia> whom = "world"
"world"
julia> string(greet, ", ", whom, ".\n")
"Hello, world.\n"
Constructing strings like this can become a bit cumbersome, however. To reduce the need for these verbose calls to
string, Julia allows interpolation into string literals using $, as in Perl:
julia> "$greet, $whom.\n"
"Hello, world.\n"
This is more readable and convenient and equivalent to the above string concatenation the system rewrites this
apparent single string literal into a concatenation of string literals with variables.
The shortest complete expression after the $ is taken as the expression whose value is to be interpolated into the string.
Thus, you can interpolate any expression into a string using parentheses:
julia> "1 + 2 = $(1 + 2)"
"1 + 2 = 3"
Both concatenation and string interpolation call the generic string function to convert objects into String form.
Most non-String objects are converted to strings as they are shown in interactive sessions:
julia> v = [1,2,3]
3-element Array{Int64,1}:
1
2
3
julia> "v: $v"
"v: [1,2,3]"
The string function is the identity for String and Char values, so these are interpolated into strings as themselves,
unquoted and unescaped:
34 Chapter 1. The Julia Manual
Julia Language Documentation, Release 0.4.0-dev
julia> c = x
x
julia> "hi, $c"
"hi, x"
To include a literal $ in a string literal, escape it with a backslash:
julia> print("I have \$100 in my account.\n")
I have $100 in my account.
1.7.5 Common Operations
You can lexicographically compare strings using the standard comparison operators:
julia> "abracadabra" < "xylophone"
true
julia> "abracadabra" == "xylophone"
false
julia> "Hello, world." != "Goodbye, world."
true
julia> "1 + 2 = 3" == "1 + 2 = $(1 + 2)"
true
You can search for the index of a particular character using the search function:
julia> search("xylophone", x)
1
julia> search("xylophone", p)
5
julia> search("xylophone", z)
0
You can start the search for a character at a given offset by providing a third argument:
julia> search("xylophone", o)
4
julia> search("xylophone", o, 5)
7
julia> search("xylophone", o, 8)
0
Another handy string function is repeat:
julia> repeat(".:Z:.", 10)
".:Z:..:Z:..:Z:..:Z:..:Z:..:Z:..:Z:..:Z:..:Z:..:Z:."
Some other useful functions include:
endof(str) gives the maximal (byte) index that can be used to index into str.
length(str) the number of characters in str.
1.7. Strings 35
Julia Language Documentation, Release 0.4.0-dev
i = start(str) gives the rst valid index at which a character can be found in str (typically 1).
c, j = next(str,i) returns next character at or after the index i and the next valid character index
following that. With start and endof, can be used to iterate through the characters in str.
ind2chr(str,i) gives the number of characters in str up to and including any at index i.
chr2ind(str,j) gives the index at which the jth character in str occurs.
1.7.6 Non-Standard String Literals
There are situations when you want to construct a string or use string semantics, but the behavior of the standard string
construct is not quite what is needed. For these kinds of situations, Julia provides non-standard string literals. A non-
standard string literal looks like a regular double-quoted string literal, but is immediately prexed by an identier, and
doesnt behave quite like a normal string literal. Regular expressions, byte array literals and version number literals, as
described below, are some examples of non-standard string literals. Other examples are given in the metaprogramming
section.
1.7.7 Regular Expressions
Julia has Perl-compatible regular expressions (regexes), as provided by the PCRE library. Regular expressions are
related to strings in two ways: the obvious connection is that regular expressions are used to nd regular patterns in
strings; the other connection is that regular expressions are themselves input as strings, which are parsed into a state
machine that can be used to efciently search for patterns in strings. In Julia, regular expressions are input using non-
standard string literals prexed with various identiers beginning with r. The most basic regular expression literal
without any options turned on just uses r"...":
julia> r"^\s
*
(?:#|$)"
r"^\s
*
(?:#|$)"
julia> typeof(ans)
Regex (constructor with 3 methods)
To check if a regex matches a string, use the ismatch function:
julia> ismatch(r"^\s
*
(?:#|$)", "not a comment")
false
julia> ismatch(r"^\s
*
(?:#|$)", "# a comment")
true
As one can see here, ismatch simply returns true or false, indicating whether the given regex matches the string or
not. Commonly, however, one wants to know not just whether a string matched, but also how it matched. To capture
this information about a match, use the match function instead:
julia> match(r"^\s
*
(?:#|$)", "not a comment")
julia> match(r"^\s
*
(?:#|$)", "# a comment")
RegexMatch("#")
If the regular expression does not match the given string, match returns nothing a special value that does not
print anything at the interactive prompt. Other than not printing, it is a completely normal value and you can test for it
programmatically:
m = match(r"^\s
*
(?:#|$)", line)
if m == nothing
println("not a comment")
36 Chapter 1. The Julia Manual
Julia Language Documentation, Release 0.4.0-dev
else
println("blank or comment")
end
If a regular expression does match, the value returned by match is a RegexMatch object. These objects record how
the expression matches, including the substring that the pattern matches and any captured substrings, if there are any.
This example only captures the portion of the substring that matches, but perhaps we want to capture any non-blank
text after the comment character. We could do the following:
julia> m = match(r"^\s
*
(?:#\s
*
(.
*
?)\s
*
$|$)", "# a comment ")
RegexMatch("# a comment ", 1="a comment")
When calling match, you have the option to specify an index at which to start the search. For example:
julia> m = match(r"[0-9]","aaaa1aaaa2aaaa3",1)
RegexMatch("1")
julia> m = match(r"[0-9]","aaaa1aaaa2aaaa3",6)
RegexMatch("2")
julia> m = match(r"[0-9]","aaaa1aaaa2aaaa3",11)
RegexMatch("3")
You can extract the following info from a RegexMatch object:
the entire substring matched: m.match
the captured substrings as a tuple of strings: m.captures
the offset at which the whole match begins: m.offset
the offsets of the captured substrings as a vector: m.offsets
For when a capture doesnt match, instead of a substring, m.captures contains nothing in that position, and
m.offsets has a zero offset (recall that indices in Julia are 1-based, so a zero offset into a string is invalid). Heres
is a pair of somewhat contrived examples:
julia> m = match(r"(a|b)(c)?(d)", "acd")
RegexMatch("acd", 1="a", 2="c", 3="d")
julia> m.match
"acd"
julia> m.captures
3-element Array{Union(SubString{UTF8String},Nothing),1}:
"a"
"c"
"d"
julia> m.offset
1
julia> m.offsets
3-element Array{Int64,1}:
1
2
3
julia> m = match(r"(a|b)(c)?(d)", "ad")
RegexMatch("ad", 1="a", 2=nothing, 3="d")
1.7. Strings 37
Julia Language Documentation, Release 0.4.0-dev
julia> m.match
"ad"
julia> m.captures
3-element Array{Union(SubString{UTF8String},Nothing),1}:
"a"
nothing
"d"
julia> m.offset
1
julia> m.offsets
3-element Array{Int64,1}:
1
0
2
It is convenient to have captures returned as a tuple so that one can use tuple destructuring syntax to bind them to local
variables:
julia> first, second, third = m.captures; first
"a"
You can modify the behavior of regular expressions by some combination of the ags i, m, s, and x after the closing
double quote mark. These ags have the same meaning as they do in Perl, as explained in this excerpt from the perlre
manpage:
i Do case-insensitive pattern matching.
If locale matching rules are in effect, the case map is taken
from the current locale for code points less than 255, and
from Unicode rules for larger code points. However, matches
that would cross the Unicode rules/non-Unicode rules boundary
(ords 255/256) will not succeed.
m Treat string as multiple lines. That is, change "^" and "$"
from matching the start or end of the string to matching the
start or end of any line anywhere within the string.
s Treat string as single line. That is, change "." to match any
character whatsoever, even a newline, which normally it would
not match.
Used together, as r""ms, they let the "." match any character
whatsoever, while still allowing "^" and "$" to match,
respectively, just after and just before newlines within the
string.
x Tells the regular expression parser to ignore most whitespace
that is neither backslashed nor within a character class. You
can use this to break up your regular expression into
(slightly) more readable parts. The # character is also
treated as a metacharacter introducing a comment, just as in
ordinary code.
For example, the following regex has all three ags turned on:
38 Chapter 1. The Julia Manual
Julia Language Documentation, Release 0.4.0-dev
julia> r"a+.
*
b+.
*
?d$"ism
r"a+.
*
b+.
*
?d$"ims
julia> match(r"a+.
*
b+.
*
?d$"ism, "Goodbye,\nOh, angry,\nBad world\n")
RegexMatch("angry,\nBad world")
Triple-quoted regex strings, of the formr"""...""", are also supported (and may be convenient for regular expres-
sions containing quotation marks or newlines).
1.7.8 Byte Array Literals
Another useful non-standard string literal is the byte-array string literal: b"...". This form lets you use string
notation to express literal byte arrays i.e. arrays of Uint8 values. The convention is that non-standard literals with
uppercase prexes produce actual string objects, while those with lowercase prexes produce non-string objects like
byte arrays or compiled regular expressions. The rules for byte array literals are the following:
ASCII characters and ASCII escapes produce a single byte.
\x and octal escape sequences produce the byte corresponding to the escape value.
Unicode escape sequences produce a sequence of bytes encoding that code point in UTF-8.
There is some overlap between these rules since the behavior of \x and octal escapes less than 0x80 (128) are covered
by both of the rst two rules, but here these rules agree. Together, these rules allow one to easily use ASCII characters,
arbitrary byte values, and UTF-8 sequences to produce arrays of bytes. Here is an example using all three:
julia> b"DATA\xff\u2200"
8-element Array{Uint8,1}:
0x44
0x41
0x54
0x41
0xff
0xe2
0x88
0x80
The ASCII string DATA corresponds to the bytes 68, 65, 84, 65. \xff produces the single byte 255. The Unicode
escape \u2200 is encoded in UTF-8 as the three bytes 226, 136, 128. Note that the resulting byte array does not
correspond to a valid UTF-8 string if you try to use this as a regular string literal, you will get a syntax error:
julia> "DATA\xff\u2200"
ERROR: syntax: invalid UTF-8 sequence
Also observe the signicant distinction between \xff and \uff: the former escape sequence encodes the byte 255,
whereas the latter escape sequence represents the code point 255, which is encoded as two bytes in UTF-8:
julia> b"\xff"
1-element Array{Uint8,1}:
0xff
julia> b"\uff"
2-element Array{Uint8,1}:
0xc3
0xbf
In character literals, this distinction is glossed over and \xff is allowed to represent the code point 255, because
characters always represent code points. In strings, however, \x escapes always represent bytes, not code points,
whereas \u and \U escapes always represent code points, which are encoded in one or more bytes. For code points less
1.7. Strings 39
Julia Language Documentation, Release 0.4.0-dev
than \u80, it happens that the UTF-8 encoding of each code point is just the single byte produced by the corresponding
\x escape, so the distinction can safely be ignored. For the escapes \x80 through \xff as compared to \u80 through
\uff, however, there is a major difference: the former escapes all encode single bytes, which unless followed by
very specic continuation bytes do not form valid UTF-8 data, whereas the latter escapes all represent Unicode
code points with two-byte encodings.
If this is all extremely confusing, try reading The Absolute Minimum Every Software Developer Absolutely, Posi-
tively Must Know About Unicode and Character Sets. Its an excellent introduction to Unicode and UTF-8, and may
help alleviate some confusion regarding the matter.
1.7.9 Version Number Literals
Version numbers can easily be expressed with non-standard string literals of the form v"...". Version number
literals create VersionNumber objects which follow the specications of semantic versioning, and therefore are
composed of major, minor and patch numeric values, followed by pre-release and build alpha-numeric annotations.
For example, v"0.2.1-rc1+win64" is broken into major version 0, minor version 2, patch version 1, pre-release
rc1 and build win64. When entering a version literal, everything except the major version number is optional,
therefore e.g. v"0.2" is equivalent to v"0.2.0" (with empty pre-release/build annotations), v"2" is equivalent to
v"2.0.0", and so on.
VersionNumber objects are mostly useful to easily and correctly compare two (or more) versions. For example,
the constant VERSION holds Julia version number as a VersionNumber object, and therefore one can dene some
version-specic behaviour using simple statements as:
if v"0.2" <= VERSION < v"0.3-"
# do something specific to 0.2 release series
end
Note that in the above example the non-standard version number v"0.3-" is used, with a trailing -: this notation is a
Julia extension of the standard, and its used to indicate a version which is lower than any 0.3 release, including all of
its pre-releases. So in the above example the code would only run with stable 0.2 versions, and exclude such versions
as v"0.3.0-rc1". In order to also allow for unstable (i.e. pre-release) 0.2 versions, the lower bound check should
be modied like this: v"0.2-" <= VERSION.
Another non-standard version specication extension allows to use a trailing + to express an upper limit on build
versions, e.g. VERSION > "v"0.2-rc1+" can be used to mean any version above 0.2-rc1 and any of its
builds: it will return false for version v"0.2-rc1+win64" and true for v"0.2-rc2".
It is good practice to use such special versions in comparisons (particularly, the trailing - should always be used on
upper bounds unless theres a good reason not to), but they must not be used as the actual version number of anything,
as they are invalid in the semantic versioning scheme.
Besides being used for the VERSION constant, VersionNumber objects are widely used in the Pkg module, to
specify packages versions and their dependencies.
1.8 Functions
In Julia, a function is an object that maps a tuple of argument values to a return value. Julia functions are not pure
mathematical functions, in the sense that functions can alter and be affected by the global state of the program. The
basic syntax for dening functions in Julia is:
function f(x,y)
x + y
end
40 Chapter 1. The Julia Manual
Julia Language Documentation, Release 0.4.0-dev
There is a second, more terse syntax for dening a function in Julia. The traditional function declaration syntax
demonstrated above is equivalent to the following compact assignment form:
f(x,y) = x + y
In the assignment form, the body of the function must be a single expression, although it can be a compound expression
(see Compound Expressions). Short, simple function denitions are common in Julia. The short function syntax is
accordingly quite idiomatic, considerably reducing both typing and visual noise.
A function is called using the traditional parenthesis syntax:
julia> f(2,3)
5
Without parentheses, the expression f refers to the function object, and can be passed around like any value:
julia> g = f;
julia> g(2,3)
5
There are two other ways that functions can be applied: using special operator syntax for certain function names (see
Operators Are Functions below), or with the apply function:
julia> apply(f,2,3)
5
The apply function applies its rst argument a function object to its remaining arguments.
As with variables, Unicode can also be used for function names:
julia>
(x,y) = x + y
x
2
+ y
2
avoiding overow and underow
log(x)
Compute the natural logarithm of x. Throws DomainError for negative Real arguments. Use complex
negative arguments instead.
log(b, x)
Compute the base b logarithm of x. Throws DomainError for negative Real arguments.
log2(x)
Compute the logarithm of x to base 2. Throws DomainError for negative Real arguments.
log10(x)
Compute the logarithm of x to base 10. Throws DomainError for negative Real arguments.
log1p(x)
Accurate natural logarithm of 1+x. Throws DomainError for Real arguments less than -1.
frexp(val)
Return (x,exp) such that x has a magnitude in the interval [1/2, 1) or 0, and val = x 2
exp
.
exp(x)
Compute e
x
240 Chapter 2. The Julia Standard Library
Julia Language Documentation, Release 0.4.0-dev
exp2(x)
Compute 2
x
exp10(x)
Compute 10
x
ldexp(x, n)
Compute x 2
n
modf(x)
Return a tuple (fpart,ipart) of the fractional and integral parts of a number. Both parts have the same sign as the
argument.
expm1(x)
Accurately compute e
x
1
round(x[, digits[, base ]])
round(x) returns the nearest integral value of the same type as x to x. round(x, digits) rounds to
the specied number of digits after the decimal place, or before if negative, e.g., round(pi,2) is 3.14.
round(x, digits, base) rounds using a different base, defaulting to 10, e.g., round(pi, 1, 8) is
3.125.
ceil(x[, digits[, base ]])
Returns the nearest integral value of the same type as x not less than x. digits and base work as above.
floor(x[, digits[, base ]])
Returns the nearest integral value of the same type as x not greater than x. digits and base work as above.
trunc(x[, digits[, base ]])
Returns the nearest integral value of the same type as x not greater in magnitude than x. digits and base
work as above.
iround(x) Integer
Returns the nearest integer to x.
iceil(x) Integer
Returns the nearest integer not less than x.
ifloor(x) Integer
Returns the nearest integer not greater than x.
itrunc(x) Integer
Returns the nearest integer not greater in magnitude than x.
signif(x, digits[, base ])
Rounds (in the sense of round) x so that there are digits signicant digits, under a base base representation,
default 10. E.g., signif(123.456, 2) is 120.0, and signif(357.913, 4, 2) is 352.0.
min(x, y, ...)
Return the minimum of the arguments. Operates elementwise over arrays.
max(x, y, ...)
Return the maximum of the arguments. Operates elementwise over arrays.
minmax(x, y)
Return (min(x,y), max(x,y)). See also: extrema() that returns (minimum(x), maximum(x))
clamp(x, lo, hi)
Return x if lo <= x <= hi. If x < lo, return lo. If x > hi, return hi. Arguments are promoted to a
common type. Operates elementwise over x if it is an array.
abs(x)
Absolute value of x
2.1. The Standard Library 241
Julia Language Documentation, Release 0.4.0-dev
abs2(x)
Squared absolute value of x
copysign(x, y)
Return x such that it has the same sign as y
sign(x)
Return +1 if x is positive, 0 if x == 0, and -1 if x is negative.
signbit(x)
Returns 1 if the value of the sign of x is negative, otherwise 0.
flipsign(x, y)
Return x with its sign ipped if y is negative. For example abs(x) = flipsign(x,x).
sqrt(x)
Return
x. Throws DomainError for negative Real arguments. Use complex negative arguments instead.
The prex operator
is equivalent to sqrt.
isqrt(n)
Integer square root: the largest integer m such that m
*
m <= n.
cbrt(x)
Return x
1/3
. The prex operator 3
is equivalent to cbrt.
erf(x)
Compute the error function of x, dened by
2
x
0
e
t
2
dt for arbitrary complex x.
erfc(x)
Compute the complementary error function of x, dened by 1 erf(x).
erfcx(x)
Compute the scaled complementary error function of x, dened by e
x
2
erfc(x). Note also that erfcx(ix)
computes the Faddeeva function w(x).
erfi(x)
Compute the imaginary error function of x, dened by i erf(ix).
dawson(x)
Compute the Dawson function (scaled imaginary error function) of x, dened by
2
e
x
2
er(x).
erfinv(x)
Compute the inverse error function of a real x, dened by erf(ernv(x)) = x.
erfcinv(x)
Compute the inverse error complementary function of a real x, dened by erfc(erfcinv(x)) = x.
real(z)
Return the real part of the complex number z
imag(z)
Return the imaginary part of the complex number z
reim(z)
Return both the real and imaginary parts of the complex number z
conj(z)
Compute the complex conjugate of a complex number z
angle(z)
Compute the phase angle of a complex number z
cis(z)
Return exp(iz).
242 Chapter 2. The Julia Standard Library
Julia Language Documentation, Release 0.4.0-dev
binomial(n, k)
Number of ways to choose k out of n items
factorial(n)
Factorial of n
factorial(n, k)
Compute factorial(n)/factorial(k)
factor(n) Dict
Compute the prime factorization of an integer n. Returns a dictionary. The keys of the dictionary correspond
to the factors, and hence are of the same type as n. The value associated with each key indicates the number of
times the factor appears in the factorization.
julia> factor(100) # == 2
*
2
*
5
*
5
Dict{Int64,Int64} with 2 entries:
2 => 2
5 => 2
gcd(x, y)
Greatest common (positive) divisor (or zero if x and y are both zero).
lcm(x, y)
Least common (non-negative) multiple.
gcdx(x, y)
Computes the greatest common (positive) divisor of x and y and their Bzout coefcients, i.e. the integer
coefcients u and v that satisfy ux + vy = d = gcd(x, y).
julia> gcdx(12, 42)
(6,-3,1)
julia> gcdx(240, 46)
(2,-9,47)
Note: Bzout coefcients are not uniquely dened. gcdx returns the minimal Bzout coefcients that are
computed by the extended Euclid algorithm. (Ref: D. Knuth, TAoCP, 2/e, p. 325, Algorithm X.) These coef-
cients u and v are minimal in the sense that |u| < |
y
d
and |v| < |
x
d
. Furthermore, the signs of u and v are chosen
so that d is positive.
ispow2(n) Bool
Test whether n is a power of two
nextpow2(n)
The smallest power of two not less than n. Returns 0 for n==0, and returns -nextpow2(-n) for negative
arguments.
prevpow2(n)
The largest power of two not greater than n. Returns 0 for n==0, and returns -prevpow2(-n) for negative
arguments.
nextpow(a, x)
The smallest a^n not less than x, where n is a non-negative integer. a must be greater than 1, and x must be
greater than 0.
prevpow(a, x)
The largest a^n not greater than x, where n is a non-negative integer. a must be greater than 1, and x must not
be less than 1.
2.1. The Standard Library 243
Julia Language Documentation, Release 0.4.0-dev
nextprod([k_1, k_2, ... ], n)
Next integer not less than n that can be written as
k
pi
i
for integers p
1
, p
2
, etc.
prevprod([k_1, k_2, ... ], n)
Previous integer not greater than n that can be written as
k
pi
i
for integers p
1
, p
2
, etc.
invmod(x, m)
Take the inverse of x modulo m: y such that xy = 1 (mod m)
powermod(x, p, m)
Compute x
p
(mod m)
gamma(x)
Compute the gamma function of x
lgamma(x)
Compute the logarithm of absolute value of gamma(x)
lfact(x)
Compute the logarithmic factorial of x
digamma(x)
Compute the digamma function of x (the logarithmic derivative of gamma(x))
invdigamma(x)
Compute the inverse digamma function of x.
trigamma(x)
Compute the trigamma function of x (the logarithmic second derivative of gamma(x))
polygamma(m, x)
Compute the polygamma function of order m of argument x (the (m+1)th derivative of the logarithm of
gamma(x))
airy(k, x)
kth derivative of the Airy function Ai(x).
airyai(x)
Airy function Ai(x).
airyprime(x)
Airy function derivative Ai
(x).
airyaiprime(x)
Airy function derivative Ai
(x).
airybi(x)
Airy function Bi(x).
airybiprime(x)
Airy function derivative Bi
(x).
airyx(k, x)
scaled kth derivative of the Airy function, return Ai(x)e
2
3
x
x
for k == 0 || k == 1, and
Ai(x)e
|Re(
2
3
x
x)|
for k == 2 || k == 3.
besselj0(x)
Bessel function of the rst kind of order 0, J
0
(x).
besselj1(x)
Bessel function of the rst kind of order 1, J
1
(x).
besselj(nu, x)
Bessel function of the rst kind of order nu, J
(x).
244 Chapter 2. The Julia Standard Library
Julia Language Documentation, Release 0.4.0-dev
besseljx(nu, x)
Scaled Bessel function of the rst kind of order nu, J
(x)e
| Im(x)|
.
bessely0(x)
Bessel function of the second kind of order 0, Y
0
(x).
bessely1(x)
Bessel function of the second kind of order 1, Y
1
(x).
bessely(nu, x)
Bessel function of the second kind of order nu, Y
(x).
besselyx(nu, x)
Scaled Bessel function of the second kind of order nu, Y
(x)e
| Im(x)|
.
hankelh1(nu, x)
Bessel function of the third kind of order nu, H
(1)
(x).
hankelh1x(nu, x)
Scaled Bessel function of the third kind of order nu, H
(1)
(x)e
xi
.
hankelh2(nu, x)
Bessel function of the third kind of order nu, H
(2)
(x).
hankelh2x(nu, x)
Scaled Bessel function of the third kind of order nu, H
(2)
(x)e
xi
.
besselh(nu, k, x)
Bessel function of the third kind of order nu (Hankel function). k is either 1 or 2, selecting hankelh1 or
hankelh2, respectively.
besseli(nu, x)
Modied Bessel function of the rst kind of order nu, I
(x).
besselix(nu, x)
Scaled modied Bessel function of the rst kind of order nu, I
(x)e
| Re(x)|
.
besselk(nu, x)
Modied Bessel function of the second kind of order nu, K
(x).
besselkx(nu, x)
Scaled modied Bessel function of the second kind of order nu, K
(x)e
x
.
beta(x, y)
Euler integral of the rst kind B(x, y) = (x)(y)/(x + y).
lbeta(x, y)
Natural logarithm of the absolute value of the beta function log(| B(x, y)|).
eta(x)
Dirichlet eta function (s) =
n=1
()
n1
/n
s
.
zeta(s)
Riemann zeta function (s).
zeta(s, z)
Hurwitz zeta function (s, z). (This is equivalent to the Riemann zeta function (s) for the case of z=1.)
ndigits(n, b)
Compute the number of digits in number n written in base b.
widemul(x, y)
Multiply x and y, giving the result as a larger type.
2.1. The Standard Library 245
Julia Language Documentation, Release 0.4.0-dev
@evalpoly(z, c...)
Evaluate the polynomial
k
c[k]z
k1
for the coefcients c[1], c[2], ...; that is, the coefcients are given in
ascending order by power of z. This macro expands to efcient inline code that uses either Horners method or,
for complex z, a more efcient Goertzel-like algorithm.
2.1.23 Data Formats
bin(n[, pad ])
Convert an integer to a binary string, optionally specifying a number of digits to pad to.
hex(n[, pad ])
Convert an integer to a hexadecimal string, optionally specifying a number of digits to pad to.
dec(n[, pad ])
Convert an integer to a decimal string, optionally specifying a number of digits to pad to.
oct(n[, pad ])
Convert an integer to an octal string, optionally specifying a number of digits to pad to.
base(base, n[, pad ])
Convert an integer to a string in the given base, optionally specifying a number of digits to pad to. The base can
be specied as either an integer, or as a Uint8 array of character values to use as digit symbols.
digits(n[, base ][, pad ])
Returns an array of the digits of n in the given base, optionally padded with zeros to a specied size.
More signicant digits are at higher indexes, such that n == sum([digits[k]
*
base^(k-1) for
k=1:length(digits)]).
digits!(array, n[, base ])
Fills an array of the digits of n in the given base. More signicant digits are at higher indexes. If the array length
is insufcient, the least signicant digits are lled up to the array length. If the array length is excessive, the
excess portion is lled with zeros.
bits(n)
A string giving the literal bit representation of a number.
parseint([type ], str[, base ])
Parse a string as an integer in the given base (default 10), yielding a number of the specied type (default Int).
parsefloat([type ], str)
Parse a string as a decimal oating point number, yielding a number of the specied type.
big(x)
Convert a number to a maximum precision representation (typically BigInt or BigFloat). See BigFloat
for information about some pitfalls with oating-point numbers.
bool(x)
Convert a number or numeric array to boolean
int(x)
Convert a number or array to the default integer type on your platform. Alternatively, x can be a string, which
is parsed as an integer.
uint(x)
Convert a number or array to the default unsigned integer type on your platform. Alternatively, x can be a string,
which is parsed as an unsigned integer.
integer(x)
Convert a number or array to integer type. If x is already of integer type it is unchanged, otherwise it converts it
to the default integer type on your platform.
246 Chapter 2. The Julia Standard Library
Julia Language Documentation, Release 0.4.0-dev
signed(x)
Convert a number to a signed integer
unsigned(x) Unsigned
Convert a number to an unsigned integer
int8(x)
Convert a number or array to Int8 data type
int16(x)
Convert a number or array to Int16 data type
int32(x)
Convert a number or array to Int32 data type
int64(x)
Convert a number or array to Int64 data type
int128(x)
Convert a number or array to Int128 data type
uint8(x)
Convert a number or array to Uint8 data type
uint16(x)
Convert a number or array to Uint16 data type
uint32(x)
Convert a number or array to Uint32 data type
uint64(x)
Convert a number or array to Uint64 data type
uint128(x)
Convert a number or array to Uint128 data type
float16(x)
Convert a number or array to Float16 data type
float32(x)
Convert a number or array to Float32 data type
float64(x)
Convert a number or array to Float64 data type
float32_isvalid(x, out::Vector{Float32}) Bool
Convert a number or array to Float32 data type, returning true if successful. The result of the conversion is
stored in out[1].
float64_isvalid(x, out::Vector{Float64}) Bool
Convert a number or array to Float64 data type, returning true if successful. The result of the conversion is
stored in out[1].
float(x)
Convert a number, array, or string to a FloatingPoint data type. For numeric data, the smallest suitable
FloatingPoint type is used. Converts strings to Float64.
This function is not recommended for arrays. It is better to use a more specic function such as float32 or
float64.
significand(x)
Extract the signicand(s) (a.k.a. mantissa), in binary representation, of a oating-point number or array.
2.1. The Standard Library 247
Julia Language Documentation, Release 0.4.0-dev
julia> significand(15.2)/15.2
0.125
julia> significand(15.2)
*
8
15.2
exponent(x) Int
Get the exponent of a normalized oating-point number.
complex64(r[, i ])
Convert to r + i
*
im represented as a Complex64 data type. i defaults to zero.
complex128(r[, i ])
Convert to r + i
*
im represented as a Complex128 data type. i defaults to zero.
complex(r[, i ])
Convert real numbers or arrays to complex. i defaults to zero.
char(x)
Convert a number or array to Char data type
bswap(n)
Byte-swap an integer
num2hex(f )
Get a hexadecimal string of the binary representation of a oating point number
hex2num(str)
Convert a hexadecimal string to the oating point number it represents
hex2bytes(s::ASCIIString)
Convert an arbitrarily long hexadecimal string to its binary representation. Returns an Array{Uint8, 1}, i.e. an
array of bytes.
bytes2hex(bin_arr::Array{Uint8, 1})
Convert an array of bytes to its hexadecimal representation. All characters are in lower-case. Returns an ASCI-
IString.
2.1.24 Numbers
one(x)
Get the multiplicative identity element for the type of x (x can also specify the type itself). For matrices, returns
an identity matrix of the appropriate size and type.
zero(x)
Get the additive identity element for the type of x (x can also specify the type itself).
pi
The constant pi
im
The imaginary unit
e
The constant e
catalan
Catalans constant
248 Chapter 2. The Julia Standard Library
Julia Language Documentation, Release 0.4.0-dev
Eulers constant
n=1
exp
(
i
2(n 1)(k 1)
length(A)
)
A[n].
A multidimensional FFT simply performs this operation along each transformed dimension of A.
fft!(A[, dims ])
Same as fft(), but operates in-place on A, which must be an array of complex oating-point numbers.
ifft(A[, dims ])
Multidimensional inverse FFT.
A one-dimensional inverse FFT computes
IDFT(A)[k] =
1
length(A)
length(A)
n=1
exp
(
+i
2(n 1)(k 1)
length(A)
)
A[n].
A multidimensional inverse FFT simply performs this operation along each transformed dimension of A.
ifft!(A[, dims ])
Same as ifft(), but operates in-place on A.
bfft(A[, dims ])
Similar to ifft(), but computes an unnormalized inverse (backward) transform, which must be divided by
the product of the sizes of the transformed dimensions in order to obtain the inverse. (This is slightly more
2.1. The Standard Library 261
Julia Language Documentation, Release 0.4.0-dev
efcient than ifft() because it omits a scaling step, which in some applications can be combined with other
computational steps elsewhere.)
BDFT(A)[k] = length(A) IDFT(A)[k]
bfft!(A[, dims ])
Same as bfft(), but operates in-place on A.
plan_fft(A[, dims[, ags[, timelimit ]]])
Pre-plan an optimized FFT along given dimensions (dims) of arrays matching the shape and type of A. (The rst
two arguments have the same meaning as for fft().) Returns a function plan(A) that computes fft(A,
dims) quickly.
The flags argument is a bitwise-or of FFTW planner ags, defaulting to FFTW.ESTIMATE. e.g. passing
FFTW.MEASURE or FFTW.PATIENT will instead spend several seconds (or more) benchmarking different
possible FFT algorithms and picking the fastest one; see the FFTW manual for more information on planner
ags. The optional timelimit argument species a rough upper bound on the allowed planning time, in
seconds. Passing FFTW.MEASURE or FFTW.PATIENT may cause the input array A to be overwritten with
zeros during plan creation.
plan_fft!() is the same as plan_fft() but creates a plan that operates in-place on its argument (which
must be an array of complex oating-point numbers). plan_ifft() and so on are similar but produce plans
that perform the equivalent of the inverse transforms ifft() and so on.
plan_ifft(A[, dims[, ags[, timelimit ]]])
Same as plan_fft(), but produces a plan that performs inverse transforms ifft().
plan_bfft(A[, dims[, ags[, timelimit ]]])
Same as plan_fft(), but produces a plan that performs an unnormalized backwards transform bfft().
plan_fft!(A[, dims[, ags[, timelimit ]]])
Same as plan_fft(), but operates in-place on A.
plan_ifft!(A[, dims[, ags[, timelimit ]]])
Same as plan_ifft(), but operates in-place on A.
plan_bfft!(A[, dims[, ags[, timelimit ]]])
Same as plan_bfft(), but operates in-place on A.
rfft(A[, dims ])
Multidimensional FFT of a real array A, exploiting the fact that the transform has conjugate symmetry in order
to save roughly half the computational time and storage costs compared with fft(). If A has size (n_1,
..., n_d), the result has size (floor(n_1/2)+1, ..., n_d).
The optional dims argument species an iterable subset of one or more dimensions of A to transform, similar to
fft(). Instead of (roughly) halving the rst dimension of A in the result, the dims[1] dimension is (roughly)
halved in the same way.
irfft(A, d[, dims ])
Inverse of rfft(): for a complex array A, gives the corresponding real array whose FFT yields A in the rst
half. As for rfft(), dims is an optional subset of dimensions to transform, defaulting to 1:ndims(A).
d is the length of the transformed real array along the dims[1] dimension, which must satisfy d ==
floor(size(A,dims[1])/2)+1. (This parameter cannot be inferred from size(A) due to the pos-
sibility of rounding by the floor function here.)
brfft(A, d[, dims ])
Similar to irfft() but computes an unnormalized inverse transform (similar to bfft()), which must be
divided by the product of the sizes of the transformed dimensions (of the real output array) in order to obtain the
inverse transform.
262 Chapter 2. The Julia Standard Library
Julia Language Documentation, Release 0.4.0-dev
plan_rfft(A[, dims[, ags[, timelimit ]]])
Pre-plan an optimized real-input FFT, similar to plan_fft() except for rfft() instead of fft(). The rst
two arguments, and the size of the transformed result, are the same as for rfft().
plan_brfft(A, d[, dims[, ags[, timelimit ]]])
Pre-plan an optimized real-input unnormalized transform, similar to plan_rfft() except for brfft() in-
stead of rfft(). The rst two arguments and the size of the transformed result, are the same as for brfft().
plan_irfft(A, d[, dims[, ags[, timelimit ]]])
Pre-plan an optimized inverse real-input FFT, similar to plan_rfft() except for irfft() and brfft(),
respectively. The rst three arguments have the same meaning as for irfft().
dct(A[, dims ])
Performs a multidimensional type-II discrete cosine transform (DCT) of the array A, using the unitary normal-
ization of the DCT. The optional dims argument species an iterable subset of dimensions (e.g. an integer,
range, tuple, or array) to transform along. Most efcient if the size of A along the transformed dimensions is a
product of small primes; see nextprod(). See also plan_dct() for even greater efciency.
dct!(A[, dims ])
Same as dct!(), except that it operates in-place on A, which must be an array of real or complex oating-point
values.
idct(A[, dims ])
Computes the multidimensional inverse discrete cosine transform (DCT) of the array A (technically, a type-III
DCT with the unitary normalization). The optional dims argument species an iterable subset of dimensions
(e.g. an integer, range, tuple, or array) to transform along. Most efcient if the size of A along the trans-
formed dimensions is a product of small primes; see nextprod(). See also plan_idct() for even greater
efciency.
idct!(A[, dims ])
Same as idct!(), but operates in-place on A.
plan_dct(A[, dims[, ags[, timelimit ]]])
Pre-plan an optimized discrete cosine transform (DCT), similar to plan_fft() except producing a function
that computes dct(). The rst two arguments have the same meaning as for dct().
plan_dct!(A[, dims[, ags[, timelimit ]]])
Same as plan_dct(), but operates in-place on A.
plan_idct(A[, dims[, ags[, timelimit ]]])
Pre-plan an optimized inverse discrete cosine transform (DCT), similar to plan_fft() except producing a
function that computes idct(). The rst two arguments have the same meaning as for idct().
plan_idct!(A[, dims[, ags[, timelimit ]]])
Same as plan_idct(), but operates in-place on A.
fftshift(x)
Swap the rst and second halves of each dimension of x.
fftshift(x, dim)
Swap the rst and second halves of the given dimension of array x.
ifftshift(x[, dim])
Undoes the effect of fftshift.
filt(b, a, x[, si ])
Apply lter described by vectors a and b to vector x, with an optional initial lter state vector si (defaults to
zeros).
filt!(out, b, a, x[, si ])
Same as filt() but writes the result into the out argument, which may alias the input x to modify it in-place.
2.1. The Standard Library 263
Julia Language Documentation, Release 0.4.0-dev
deconv(b, a)
Construct vector c such that b = conv(a,c) + r. Equivalent to polynomial division.
conv(u, v)
Convolution of two vectors. Uses FFT algorithm.
conv2(u, v, A)
2-D convolution of the matrix A with the 2-D separable kernel generated by the vectors u and v. Uses 2-D FFT
algorithm
conv2(B, A)
2-D convolution of the matrix B with the matrix A. Uses 2-D FFT algorithm
xcorr(u, v)
Compute the cross-correlation of two vectors.
The following functions are dened within the Base.FFTW module.
r2r(A, kind[, dims ])
Performs a multidimensional real-input/real-output (r2r) transform of type kind of the array A, as dened
in the FFTW manual. kind species either a discrete cosine transform of various types (FFTW.REDFT00,
FFTW.REDFT01, FFTW.REDFT10, or FFTW.REDFT11), a discrete sine transform of various types
(FFTW.RODFT00, FFTW.RODFT01, FFTW.RODFT10, or FFTW.RODFT11), a real-input DFT with
halfcomplex-format output (FFTW.R2HC and its inverse FFTW.HC2R), or a discrete Hartley transform
(FFTW.DHT). The kind argument may be an array or tuple in order to specify different transform types along
the different dimensions of A; kind[end] is used for any unspecied dimensions. See the FFTW manual for
precise denitions of these transform types, at http://www.fftw.org/doc.
The optional dims argument species an iterable subset of dimensions (e.g. an integer, range, tuple, or array)
to transform along. kind[i] is then the transform type for dims[i], with kind[end] being used for i >
length(kind).
See also plan_r2r() to pre-plan optimized r2r transforms.
r2r!(A, kind[, dims ])
Same as r2r(), but operates in-place on A, which must be an array of real or complex oating-point numbers.
plan_r2r(A, kind[, dims[, ags[, timelimit ]]])
Pre-plan an optimized r2r transform, similar to Base.plan_fft() except that the transforms (and the rst
three arguments) correspond to r2r() and r2r!(), respectively.
plan_r2r!(A, kind[, dims[, ags[, timelimit ]]])
Similar to Base.plan_fft(), but corresponds to r2r!().
2.1.31 Numerical Integration
Although several external packages are available for numeric integration and solution of ordinary differential equa-
tions, we also provide some built-in integration support in Julia.
quadgk(f, a, b, c...; reltol=sqrt(eps), abstol=0, maxevals=10^7, order=7, norm=vecnorm)
Numerically integrate the function f(x) from a to b, and optionally over additional intervals b to c and so
on. Keyword options include a relative error tolerance reltol (defaults to sqrt(eps) in the precision of
the endpoints), an absolute error tolerance abstol (defaults to 0), a maximum number of function evaluations
maxevals (defaults to 10^7), and the order of the integration rule (defaults to 7).
Returns a pair (I,E) of the estimated integral I and an estimated upper bound on the absolute error E. If
maxevals is not exceeded then E <= max(abstol, reltol
*
norm(I)) will hold. (Note that it is
useful to specify a positive abstol in cases where norm(I) may be zero.)
264 Chapter 2. The Julia Standard Library
Julia Language Documentation, Release 0.4.0-dev
The endpoints a etcetera can also be complex (in which case the integral is performed over straight-line segments
in the complex plane). If the endpoints are BigFloat, then the integration will be performed in BigFloat
precision as well (note: it is advisable to increase the integration order in rough proportion to the precision, for
smooth integrands). More generally, the precision is set by the precision of the integration endpoints (promoted
to oating-point types).
The integrand f(x) can return any numeric scalar, vector, or matrix type, or in fact any type supporting +, -,
multiplication by real values, and a norm (i.e., any normed vector space). Alternatively, a different norm can
be specied by passing a norm-like function as the norm keyword argument (which defaults to vecnorm).
The algorithm is an adaptive Gauss-Kronrod integration technique: the integral in each interval is estimated
using a Kronrod rule (2
*
order+1 points) and the error is estimated using an embedded Gauss rule (order
points). The interval with the largest error is then subdivided into two intervals and the process is repeated until
the desired error tolerance is achieved.
These quadrature rules work best for smooth functions within each interval, so if your function has a known
discontinuity or other singularity, it is best to subdivide your interval to put the singularity at an endpoint. For
example, if f has a discontinuity at x=0.7 and you want to integrate from 0 to 1, you should use quadgk(f,
0,0.7,1) to subdivide the interval at the point of discontinuity. The integrand is never evaluated exactly at
the endpoints of the intervals, so it is possible to integrate functions that diverge at the endpoints as long as the
singularity is integrable (for example, a log(x) or 1/sqrt(x) singularity).
For real-valued endpoints, the starting and/or ending points may be innite. (A coordinate transformation is
performed internally to map the innite interval to a nite one.)
2.1.32 Parallel Computing
addprocs(n; cman::ClusterManager=LocalManager()) List of process identiers
addprocs(4) will add 4 processes on the local machine. This can be used to take advantage of multiple
cores.
Keyword argument cman can be used to provide a custom cluster manager to start workers. For example
Beowulf clusters are supported via a custom cluster manager implemented in package ClusterManagers.
See the documentation for package ClusterManagers for more information on howto write a customcluster
manager.
addprocs(machines; tunnel=false, dir=JULIA_HOME, sshags::Cmd=) List of process identiers
Add processes on remote machines via SSH. Requires julia to be installed in the same location on each node, or
to be available via a shared le system.
machines is a vector of host denitions of the form [user@]host[:port] [bind_addr]. user
defaults to current user, port to the standard ssh port. Optionally, in case of multi-homed hosts, bind_addr
may be used to explicitly specify an interface.
Keyword arguments:
tunnel : if true then SSH tunneling will be used to connect to the worker.
dir : species the location of the julia binaries on the worker nodes.
sshflags : species additional ssh options, e.g. sshflags=-i /home/foo/bar.pem .
nprocs()
Get the number of available processes.
nworkers()
Get the number of available worker processes. This is one less than nprocs(). Equal to nprocs() if nprocs() == 1.
procs()
Returns a list of all process identiers.
2.1. The Standard Library 265
Julia Language Documentation, Release 0.4.0-dev
workers()
Returns a list of all worker process identiers.
rmprocs(pids...)
Removes the specied workers.
interrupt([pids... ])
Interrupt the current executing task on the specied workers. This is equivalent to pressing Ctrl-C on the local
machine. If no arguments are given, all workers are interrupted.
myid()
Get the id of the current process.
pmap(f, lsts...; err_retry=true, err_stop=false)
Transform collections lsts by applying f to each element in parallel. If nprocs() > 1, the calling process
will be dedicated to assigning tasks. All other available processes will be used as parallel workers.
If err_retry is true, it retries a failed application of f on a different worker. If err_stop is true, it takes
precedence over the value of err_retry and pmap stops execution on the rst error.
remotecall(id, func, args...)
Call a function asynchronously on the given arguments on the specied process. Returns a RemoteRef.
wait([x ])
Block the current task until some event occurs, depending on the type of the argument:
RemoteRef: Wait for a value to become available for the specied remote reference.
Condition: Wait for notify on a condition.
Process: Wait for a process or process chain to exit. The exitcode eld of a process can be used to
determine success or failure.
Task: Wait for a Task to nish, returning its result value.
RawFD: Wait for changes on a le descriptor (see poll_fd for keyword arguments and return code)
If no argument is passed, the task blocks for an undened period. If the tasks state is set to :waiting, it can
only be restarted by an explicit call to schedule or yieldto. If the tasks state is :runnable, it might be
restarted unpredictably.
Often wait is called within a while loop to ensure a waited-for condition is met before proceeding.
fetch(RemoteRef )
Wait for and get the value of a remote reference.
remotecall_wait(id, func, args...)
Perform wait(remotecall(...)) in one message.
remotecall_fetch(id, func, args...)
Perform fetch(remotecall(...)) in one message.
put!(RemoteRef, value)
Store a value to a remote reference. Implements shared queue of length 1 semantics: if a value is already
present, blocks until the value is removed with take!. Returns its rst argument.
take!(RemoteRef )
Fetch the value of a remote reference, removing it so that the reference is empty again.
isready(r::RemoteRef )
Determine whether a RemoteRef has a value stored to it. Note that this function can cause race conditions,
since by the time you receive its result it may no longer be true. It is recommended that this function only be
used on a RemoteRef that is assigned once.
266 Chapter 2. The Julia Standard Library
Julia Language Documentation, Release 0.4.0-dev
If the argument RemoteRef is owned by a different node, this call will block to wait for the answer. It is
recommended to wait for r in a separate task instead, or to use a local RemoteRef as a proxy:
rr = RemoteRef()
@async put!(rr, remotecall_fetch(p, long_computation))
isready(rr) # will not block
RemoteRef()
Make an uninitialized remote reference on the local machine.
RemoteRef(n)
Make an uninitialized remote reference on process n.
timedwait(testcb::Function, secs::Float64; pollint::Float64=0.1)
Waits till testcb returns true or for secs seconds, whichever is earlier. testcb is polled every pollint
seconds.
@spawn()
Execute an expression on an automatically-chosen process, returning a RemoteRef to the result.
@spawnat()
Accepts two arguments, p and an expression, and runs the expression asynchronously on process p, returning a
RemoteRef to the result.
@fetch()
Equivalent to fetch(@spawn expr).
@fetchfrom()
Equivalent to fetch(@spawnat p expr).
@async()
Schedule an expression to run on the local machine, also adding it to the set of items that the nearest enclosing
@sync waits for.
@sync()
Wait until all dynamically-enclosed uses of @async, @spawn, @spawnat and @parallel are complete.
@parallel()
A parallel for loop of the form
@parallel [reducer] for var = range
body
end
The specied range is partitioned and locally executed across all workers. In case an optional reducer function
is specied, @parallel performs local reductions on each worker with a nal reduction on the calling process.
Note that without a reducer function, @parallel executes asynchronously, i.e. it spawns independent tasks on all
available workers and returns immediately without waiting for completion. To wait for completion, prex the
call with @sync, like
@sync @parallel for var = range
body
end
2.1.33 Distributed Arrays
DArray(init, dims[, procs, dist ])
Construct a distributed array. The parameter init is a function that accepts a tuple of index ranges. This
function should allocate a local chunk of the distributed array and initialize it for the specied indices. dims is
2.1. The Standard Library 267
Julia Language Documentation, Release 0.4.0-dev
the overall size of the distributed array. procs optionally species a vector of process IDs to use. If unspecied,
the array is distributed over all worker processes only. Typically, when runnning in distributed mode, i.e.,
nprocs() > 1, this would mean that no chunk of the distributed array exists on the process hosting the
interactive julia prompt. dist is an integer vector specifying how many chunks the distributed array should be
divided into in each dimension.
For example, the dfill function that creates a distributed array and lls it with a value v is implemented as:
dfill(v, args...) = DArray(I->fill(v, map(length,I)), args...)
dzeros(dims, ...)
Construct a distributed array of zeros. Trailing arguments are the same as those accepted by DArray().
dones(dims, ...)
Construct a distributed array of ones. Trailing arguments are the same as those accepted by DArray().
dfill(x, dims, ...)
Construct a distributed array lled with value x. Trailing arguments are the same as those accepted by
DArray().
drand(dims, ...)
Construct a distributed uniformrandomarray. Trailing arguments are the same as those accepted by DArray().
drandn(dims, ...)
Construct a distributed normal random array. Trailing arguments are the same as those accepted by DArray().
distribute(a)
Convert a local array to distributed.
localpart(d)
Get the local piece of a distributed array. Returns an empty array if no local part exists on the calling process.
localindexes(d)
A tuple describing the indexes owned by the local process. Returns a tuple with empty ranges if no local part
exists on the calling process.
procs(d)
Get the vector of processes storing pieces of d.
2.1.34 Shared Arrays (Experimental, UNIX-only feature)
SharedArray(T::Type, dims::NTuple; init=false, pids=Int[])
Construct a SharedArray of a bitstype T and size dims across the processes specied by pids - all of which
have to be on the same host.
If pids is left unspecied, the shared array will be mapped across all workers on the current host.
If an init function of the type initfn(S::SharedArray) is specied, it is called on all the participating
workers.
procs(S::SharedArray)
Get the vector of processes that have mapped the shared array
sdata(S::SharedArray)
Returns the actual Array object backing S
indexpids(S::SharedArray)
Returns the index of the current worker into the pids vector, i.e., the list of workers mapping the SharedArray
268 Chapter 2. The Julia Standard Library
Julia Language Documentation, Release 0.4.0-dev
2.1.35 System
run(command)
Run a command object, constructed with backticks. Throws an error if anything goes wrong, including the
process exiting with a non-zero status.
spawn(command)
Run a command object asynchronously, returning the resulting Process object.
DevNull
Used in a stream redirect to discard all data written to it. Essentially equivalent to /dev/null on Unix or NUL on
Windows. Usage: run(cat test.txt |> DevNull)
success(command)
Run a command object, constructed with backticks, and tell whether it was successful (exited with a code of 0).
An exception is raised if the process cannot be started.
process_running(p::Process)
Determine whether a process is currently running.
process_exited(p::Process)
Determine whether a process has exited.
kill(p::Process, signum=SIGTERM)
Send a signal to a process. The default is to terminate the process.
open(command, mode::String=r, stdio=DevNull)
Start running command asynchronously, and return a tuple (stream,process). If mode is "r", then
stream reads from the processs standard output and stdio optionally species the processs standard input
stream. If mode is "w", then stream writes to the processs standard input and stdio optionally species
the processs standard output stream.
open(f::Function, command, mode::String=r, stdio=DevNull)
Similar to open(command, mode, stdio), but calls f(stream) on the resulting read or write stream,
then closes the stream and waits for the process to complete. Returns the value returned by f.
readandwrite(command)
Starts running a command asynchronously, and returns a tuple (stdout,stdin,process) of the output stream and
input stream of the process, and the process object itself.
ignorestatus(command)
Mark a command object so that running it will not throw an error if the result code is non-zero.
detach(command)
Mark a command object so that it will be run in a new process group, allowing it to outlive the julia process, and
not have Ctrl-C interrupts passed to it.
setenv(command, env; dir=working_dir)
Set environment variables to use when running the given command. env is either a dictionary mapping strings
to strings, or an array of strings of the form "var=val".
The dir keyword argument can be used to specify a working directory for the command.
|>(command, command)
|>(command, lename)
|>(lename, command)
Redirect operator. Used for piping the output of a process into another (rst form) or to redirect the standard
output/input of a command to/from a le (second and third forms).
Examples:
run(ls |> grep xyz)
2.1. The Standard Library 269
Julia Language Documentation, Release 0.4.0-dev
run(ls |> "out.txt")
run("out.txt" |> grep xyz)
>>(command, lename)
Redirect standard output of a process, appending to the destination le.
.>(command, lename)
Redirect the standard error stream of a process.
gethostname() String
Get the local machines host name.
getipaddr() String
Get the IP address of the local machine, as a string of the form x.x.x.x.
pwd() String
Get the current working directory.
cd(dir::String)
Set the current working directory.
cd(f [, dir ])
Temporarily changes the current working directory (HOME if not specied) and applies function f before re-
turning.
mkdir(path[, mode ])
Make a new directory with name path and permissions mode. mode defaults to 0o777, modied by the current
le creation mask.
mkpath(path[, mode ])
Create all directories in the given path, with permissions mode. mode defaults to 0o777, modied by the
current le creation mask.
symlink(target, link)
Creates a symbolic link to target with the name link.
Note: This function raises an error under operating systems that do not support soft symbolic links, such as
Windows XP.
chmod(path, mode)
Change the permissions mode of path to mode. Only integer modes (e.g. 0o777) are currently supported.
getpid() Int32
Get julias process ID.
time([t::TmStruct ])
Get the system time in seconds since the epoch, with fairly high (typically, microsecond) resolution. When
passed a TmStruct, converts it to a number of seconds since the epoch.
time_ns()
Get the time in nanoseconds. The time corresponding to 0 is undened, and wraps every 5.8 years.
strftime([format ], time)
Convert time, given as a number of seconds since the epoch or a TmStruct, to a formatted string using the
given format. Supported formats are the same as those in the standard C library.
strptime([format ], timestr)
Parse a formatted time string into a TmStruct giving the seconds, minute, hour, date, etc. Supported formats
are the same as those in the standard C library. On some platforms, timezones will not be parsed correctly. If the
result of this function will be passed to time to convert it to seconds since the epoch, the isdst eld should
270 Chapter 2. The Julia Standard Library
Julia Language Documentation, Release 0.4.0-dev
be lled in manually. Setting it to -1 will tell the C library to use the current system settings to determine the
timezone.
TmStruct([seconds ])
Convert a number of seconds since the epoch to broken-down format, with elds sec, min, hour, mday,
month, year, wday, yday, and isdst.
tic()
Set a timer to be read by the next call to toc() or toq(). The macro call @time expr can also be used to
time evaluation.
toc()
Print and return the time elapsed since the last tic().
toq()
Return, but do not print, the time elapsed since the last tic().
@time()
A macro to execute an expression, printing the time it took to execute and the total number of bytes its execution
caused to be allocated, before returning the value of the expression.
@elapsed()
A macro to evaluate an expression, discarding the resulting value, instead returning the number of seconds it
took to execute as a oating-point number.
@allocated()
A macro to evaluate an expression, discarding the resulting value, instead returning the total number of bytes
allocated during evaluation of the expression.
EnvHash() EnvHash
A singleton of this type provides a hash table interface to environment variables.
ENV
Reference to the singleton EnvHash, providing a dictionary interface to system environment variables.
@unix()
Given @unix? a : b, do a on Unix systems (including Linux and OS X) and b elsewhere. See documen-
tation for Handling Platform Variations in the Calling C and Fortran Code section of the manual.
@osx()
Given @osx? a : b, do a on OS X and b elsewhere. See documentation for Handling Platform Variations
in the Calling C and Fortran Code section of the manual.
@linux()
Given @linux? a : b, do a on Linux and b elsewhere. See documentation for Handling Platform Vari-
ations in the Calling C and Fortran Code section of the manual.
@windows()
Given @windows? a : b, do a on Windows and b elsewhere. See documentation for Handling Platform
Variations in the Calling C and Fortran Code section of the manual.
2.1.36 C Interface
ccall((symbol, library) or fptr, RetType, (ArgType1, ...), ArgVar1, ...)
Call function in C-exported shared library, specied by (function name, library) tuple, where each
component is a String or :Symbol. Alternatively, ccall may be used to call a function pointer returned by dlsym,
but note that this usage is generally discouraged to facilitate future static compilation. Note that the argument
type tuple must be a literal tuple, and not a tuple-valued variable or expression.
2.1. The Standard Library 271
Julia Language Documentation, Release 0.4.0-dev
cglobal((symbol, library) or ptr[, Type=Void ])
Obtain a pointer to a global variable in a C-exported shared library, specied exactly as in ccall. Returns a
Ptr{Type}, defaulting to Ptr{Void} if no Type argument is supplied. The values can be read or written by
unsafe_load or unsafe_store!, respectively.
cfunction(fun::Function, RetType::Type, (ArgTypes...))
Generate C-callable function pointer from Julia function. Type annotation of the return value in the callback
function is a must for situations where Julia cannot infer the return type automatically.
For example:
function foo()
# body
retval::Float64
end
bar = cfunction(foo, Float64, ())
dlopen(lible::String[, ags::Integer ])
Load a shared library, returning an opaque handle.
The optional ags argument is a bitwise-or of zero or more of RTLD_LOCAL, RTLD_GLOBAL, RTLD_LAZY,
RTLD_NOW, RTLD_NODELETE, RTLD_NOLOAD, RTLD_DEEPBIND, and RTLD_FIRST. These are con-
verted to the corresponding ags of the POSIX (and/or GNU libc and/or MacOS) dlopen command, if pos-
sible, or are ignored if the specied functionality is not available on the current platform. The default is
RTLD_LAZY|RTLD_DEEPBIND|RTLD_LOCAL. An important usage of these ags, on POSIX platforms, is
to specify RTLD_LAZY|RTLD_DEEPBIND|RTLD_GLOBAL in order for the librarys symbols to be available
for usage in other shared libraries, in situations where there are dependencies between shared libraries.
dlopen_e(lible::String[, ags::Integer ])
Similar to dlopen(), except returns a NULL pointer instead of raising errors.
RTLD_DEEPBIND
Enum constant for dlopen(). See your platform man page for details, if applicable.
RTLD_FIRST
Enum constant for dlopen(). See your platform man page for details, if applicable.
RTLD_GLOBAL
Enum constant for dlopen(). See your platform man page for details, if applicable.
RTLD_LAZY
Enum constant for dlopen(). See your platform man page for details, if applicable.
RTLD_LOCAL
Enum constant for dlopen(). See your platform man page for details, if applicable.
RTLD_NODELETE
Enum constant for dlopen(). See your platform man page for details, if applicable.
RTLD_NOLOAD
Enum constant for dlopen(). See your platform man page for details, if applicable.
RTLD_NOW
Enum constant for dlopen(). See your platform man page for details, if applicable.
dlsym(handle, sym)
Look up a symbol from a shared library handle, return callable function pointer on success.
dlsym_e(handle, sym)
Look up a symbol from a shared library handle, silently return NULL pointer on lookup failure.
272 Chapter 2. The Julia Standard Library
Julia Language Documentation, Release 0.4.0-dev
dlclose(handle)
Close shared library referenced by handle.
find_library(names, locations)
Searches for the rst library in names in the paths in the locations list, DL_LOAD_PATH, or system library
paths (in that order) which can successfully be dlopend. On success, the return value will be one of the names
(potentially prexed by one of the paths in locations). This string can be assigned to a global const and
used as the library name in future ccalls. On failure, it returns the empty string.
DL_LOAD_PATH
When calling dlopen, the paths in this list will be searched rst, in order, before searching the system locations
for a valid library handle.
c_malloc(size::Integer) Ptr{Void}
Call malloc from the C standard library.
c_calloc(num::Integer, size::Integer) Ptr{Void}
Call calloc from the C standard library.
c_realloc(addr::Ptr, size::Integer) Ptr{Void}
Call realloc from the C standard library.
c_free(addr::Ptr)
Call free from the C standard library.
unsafe_load(p::Ptr{T}, i::Integer)
Load a value of type T from the address of the ith element (1-indexed) starting at p. This is equivalent to the C
expression p[i-1].
unsafe_store!(p::Ptr{T}, x, i::Integer)
Store a value of type T to the address of the ith element (1-indexed) starting at p. This is equivalent to the C
expression p[i-1] = x.
unsafe_copy!(dest::Ptr{T}, src::Ptr{T}, N)
Copy N elements from a source pointer to a destination, with no checking. The size of an element is determined
by the type of the pointers.
unsafe_copy!(dest::Array, do, src::Array, so, N)
Copy N elements from a source array to a destination, starting at offset so in the source and do in the destination
(1-indexed).
copy!(dest, src)
Copy all elements from collection src to array dest. Returns dest.
copy!(dest, do, src, so, N)
Copy N elements from collection src starting at offset so, to array dest starting at offset do. Returns dest.
pointer(a[, index ])
Get the native address of an array or string element. Be careful to ensure that a julia reference to a exists as long
as this pointer will be used.
pointer(type, int)
Convert an integer to a pointer of the specied element type.
pointer_to_array(p, dims[, own])
Wrap a native pointer as a Julia Array object. The pointer element type determines the array element type. own
optionally species whether Julia should take ownership of the memory, calling free on the pointer when the
array is no longer referenced.
pointer_from_objref(obj)
Get the memory address of a Julia object as a Ptr. The existence of the resulting Ptr will not protect the object
2.1. The Standard Library 273
Julia Language Documentation, Release 0.4.0-dev
from garbage collection, so you must ensure that the object remains referenced for the whole time that the Ptr
will be used.
unsafe_pointer_to_objref(p::Ptr)
Convert a Ptr to an object reference. Assumes the pointer refers to a valid heap-allocated Julia object. If this
is not the case, undened behavior results, hence this function is considered unsafe and should be used with
care.
disable_sigint(f::Function)
Disable Ctrl-C handler during execution of a function, for calling external code that is not interrupt safe. In-
tended to be called using do block syntax as follows:
disable_sigint() do
# interrupt-unsafe code
...
end
reenable_sigint(f::Function)
Re-enable Ctrl-C handler during execution of a function. Temporarily reverses the effect of
disable_sigint.
errno([code ])
Get the value of the C librarys errno. If an argument is specied, it is used to set the value of errno.
The value of errno is only valid immediately after a ccall to a C library routine that sets it. Specically, you
cannot call errno at the next prompt in a REPL, because lots of code is executed between prompts.
systemerror(sysfunc, iftrue)
Raises a SystemError for errno with the descriptive string sysfunc if bool is true
strerror(n)
Convert a system call error code to a descriptive string
Cchar
Equivalent to the native char c-type
Cuchar
Equivalent to the native unsigned char c-type (Uint8)
Cshort
Equivalent to the native signed short c-type (Int16)
Cushort
Equivalent to the native unsigned short c-type (Uint16)
Cint
Equivalent to the native signed int c-type (Int32)
Cuint
Equivalent to the native unsigned int c-type (Uint32)
Clong
Equivalent to the native signed long c-type
Culong
Equivalent to the native unsigned long c-type
Clonglong
Equivalent to the native signed long long c-type (Int64)
Culonglong
Equivalent to the native unsigned long long c-type (Uint64)
274 Chapter 2. The Julia Standard Library
Julia Language Documentation, Release 0.4.0-dev
Csize_t
Equivalent to the native size_t c-type (Uint)
Cssize_t
Equivalent to the native ssize_t c-type
Cptrdiff_t
Equivalent to the native ptrdiff_t c-type (Int)
Coff_t
Equivalent to the native off_t c-type
Cwchar_t
Equivalent to the native wchar_t c-type (Int32)
Cfloat
Equivalent to the native float c-type (Float32)
Cdouble
Equivalent to the native double c-type (Float64)
2.1.37 Errors
error(message::String)
Raise an error with the given message
throw(e)
Throw an object as an exception
rethrow([e ])
Throwan object without changing the current exception backtrace. The default argument is the current exception
(if called within a catch block).
backtrace()
Get a backtrace object for the current program point.
catch_backtrace()
Get the backtrace of the current exception, for use within catch blocks.
assert(cond[, text ])
Raise an error if cond is false. Also available as the macro @assert expr.
@assert()
Raise an error if cond is false. Preferred syntax for writings assertions.
ArgumentError
The parameters given to a function call are not valid.
BoundsError
An indexing operation into an array tried to access an out-of-bounds element.
EOFError
No more data was available to read from a le or stream.
ErrorException
Generic error type. The error message, in the .msg eld, may provide more specic details.
KeyError
An indexing operation into an Associative (Dict) or Set like object tried to access or delete a non-existent
element.
2.1. The Standard Library 275
Julia Language Documentation, Release 0.4.0-dev
LoadError
An error occurred while including, requiring, or using a le. The error specics should be available in the .error
eld.
MethodError
A method with the required type signature does not exist in the given generic function.
ParseError
The expression passed to the parse function could not be interpreted as a valid Julia expression.
ProcessExitedException
After a client Julia process has exited, further attempts to reference the dead child will throw this exception.
SystemError
A system call failed with an error code (in the errno global variable).
TypeError
A type assertion failure, or calling an intrinsic function with an incorrect argument type.
2.1.38 Tasks
Task(func)
Create a Task (i.e. thread, or coroutine) to execute the given function (which must be callable with no argu-
ments). The task exits when this function returns.
yieldto(task, args...)
Switch to the given task. The rst time a task is switched to, the tasks function is called with no arguments. On
subsequent switches, args are returned from the tasks last call to yieldto. This is a low-level call that only
switches tasks, not considering states or scheduling in any way.
current_task()
Get the currently running Task.
istaskdone(task) Bool
Tell whether a task has exited.
consume(task, values...)
Receive the next value passed to produce by the specied task. Additional arguments may be passed, to be
returned from the last produce call in the producer.
produce(value)
Send the given value to the last consume call, switching to the consumer task. If the next consume call passes
any values, they are returned by produce.
yield()
Switch to the scheduler to allow another scheduled task to run. A task that calls this function is still runnable,
and will be restarted immediately if there are no other runnable tasks.
task_local_storage(symbol)
Look up the value of a symbol in the current tasks task-local storage.
task_local_storage(symbol, value)
Assign a value to a symbol in the current tasks task-local storage.
task_local_storage(body, symbol, value)
Call the function body with a modied task-local storage, in which value is assigned to symbol; the previous
value of symbol, or lack thereof, is restored afterwards. Useful for emulating dynamic scoping.
Condition()
Create an edge-triggered event source that tasks can wait for. Tasks that call wait on a Condition are
suspended and queued. Tasks are woken up when notify is later called on the Condition. Edge triggering
276 Chapter 2. The Julia Standard Library
Julia Language Documentation, Release 0.4.0-dev
means that only tasks waiting at the time notify is called can be woken up. For level-triggered notications,
you must keep extra state to keep track of whether a notication has happened. The RemoteRef type does
this, and so can be used for level-triggered events.
notify(condition, val=nothing; all=true, error=false)
Wake up tasks waiting for a condition, passing them val. If all is true (the default), all waiting tasks are
woken, otherwise only one is. If error is true, the passed value is raised as an exception in the woken tasks.
schedule(t::Task, [val]; error=false)
Add a task to the schedulers queue. This causes the task to run constantly when the system is otherwise idle,
unless the task performs a blocking operation such as wait.
If a second argument is provided, it will be passed to the task (via the return value of yieldto) when it runs
again. If error is true, the value is raised as an exception in the woken task.
@schedule()
Wrap an expression in a Task and add it to the schedulers queue.
@task()
Wrap an expression in a Task executing it, and return the Task. This only creates a task, and does not run it.
sleep(seconds)
Block the current task for a specied number of seconds. The minimum sleep time is 1 millisecond or input of
0.001.
2.1.39 Events
Timer(f::Function)
Create a timer to call the given callback function. The callback is passed one argument, the timer object itself.
The timer can be started and stopped with start_timer and stop_timer.
start_timer(t::Timer, delay, repeat)
Start invoking the callback for a Timer after the specied initial delay, and then repeating with the given
interval. Times are in seconds. If repeat is 0, the timer is only triggered once.
stop_timer(t::Timer)
Stop invoking the callback for a timer.
2.1.40 Reection
module_name(m::Module) Symbol
Get the name of a module as a symbol.
module_parent(m::Module) Module
Get a modules enclosing module. Main is its own parent.
current_module() Module
Get the dynamically current module, which is the module code is currently being read from. In general, this is
not the same as the module containing the call to this function.
fullname(m::Module)
Get the fully-qualied name of a module as a tuple of symbols. For example, fullname(Base.Pkg) gives
(:Base,:Pkg), and fullname(Main) gives ().
names(x::Module[, all=false[, imported=false ]])
Get an array of the names exported by a module, with optionally more module globals according to the additional
parameters.
2.1. The Standard Library 277
Julia Language Documentation, Release 0.4.0-dev
names(x::DataType)
Get an array of the elds of a data type.
isconst([m::Module ], s::Symbol) Bool
Determine whether a global is declared const in a given module. The default module argument is
current_module().
isgeneric(f::Function) Bool
Determine whether a function is generic.
function_name(f::Function) Symbol
Get the name of a generic function as a symbol, or :anonymous.
function_module(f::Function, types) Module
Determine the module containing a given denition of a generic function.
functionloc(f::Function, types)
Returns a tuple (filename,line) giving the location of a method denition.
functionlocs(f::Function, types)
Returns an array of the results of functionloc for all matching denitions.
2.1.41 Internals
gc()
Perform garbage collection. This should not generally be used.
gc_disable()
Disable garbage collection. This should be used only with extreme caution, as it can cause memory use to grow
without bound.
gc_enable()
Re-enable garbage collection after calling gc_disable.
macroexpand(x)
Takes the expression x and returns an equivalent expression with all macros removed (expanded).
expand(x)
Takes the expression x and returns an equivalent expression in lowered form
code_lowered(f, types)
Returns an array of lowered ASTs for the methods matching the given generic function and type signature.
@code_lowered()
Evaluates the arguments to the function call, determines their types, and calls the code_lowered function on
the resulting expression
code_typed(f, types)
Returns an array of lowered and type-inferred ASTs for the methods matching the given generic function and
type signature.
@code_typed()
Evaluates the arguments to the function call, determines their types, and calls the code_typed function on the
resulting expression
code_llvm(f, types)
Prints the LLVM bitcodes generated for running the method matching the given generic function and type
signature to STDOUT.
278 Chapter 2. The Julia Standard Library
Julia Language Documentation, Release 0.4.0-dev
@code_llvm()
Evaluates the arguments to the function call, determines their types, and calls the code_llvm function on the
resulting expression
code_native(f, types)
Prints the native assembly instructions generated for running the method matching the given generic function
and type signature to STDOUT.
@code_native()
Evaluates the arguments to the function call, determines their types, and calls the code_native function on
the resulting expression
precompile(f, args::(Any..., ))
Compile the given function f for the argument tuple (of types) args, but do not execute it.
2.2 Sparse Matrices
Sparse matrices support much of the same set of operations as dense matrices. The following functions are specic to
sparse matrices.
sparse(I, J, V[, m, n, combine ])
Create a sparse matrix S of dimensions m x n such that S[I[k], J[k]] = V[k]. The combine function
is used to combine duplicates. If m and n are not specied, they are set to max(I) and max(J) respectively.
If the combine function is not supplied, duplicates are added by default.
sparsevec(I, V[, m, combine ])
Create a sparse matrix S of size m x 1 such that S[I[k]] = V[k]. Duplicates are combined using the
combine function, which defaults to + if it is not provided. In julia, sparse vectors are really just sparse
matrices with one column. Given Julias Compressed Sparse Columns (CSC) storage format, a sparse column
matrix with one column is sparse, whereas a sparse row matrix with one row ends up being dense.
sparsevec(D::Dict[, m])
Create a sparse matrix of size m x 1 where the row values are keys from the dictionary, and the nonzero values
are the values from the dictionary.
issparse(S)
Returns true if S is sparse, and false otherwise.
sparse(A)
Convert a dense matrix A into a sparse matrix.
sparsevec(A)
Convert a dense vector A into a sparse matrix of size m x 1. In julia, sparse vectors are really just sparse
matrices with one column.
full(S)
Convert a sparse matrix S into a dense matrix.
nnz(A)
Returns the number of stored (lled) elements in a sparse matrix.
spzeros(m, n)
Create an empty sparse matrix of size m x n.
spones(S)
Create a sparse matrix with the same structure as that of S, but with every nonzero element having the value
1.0.
2.2. Sparse Matrices 279
Julia Language Documentation, Release 0.4.0-dev
speye(type, m[, n])
Create a sparse identity matrix of specied type of size m x m. In case n is supplied, create a sparse identity
matrix of size m x n.
spdiagm(B, d[, m, n])
Construct a sparse diagonal matrix. B is a tuple of vectors containing the diagonals and d is a tuple containing
the positions of the diagonals. In the case the input contains only one diagonaly, B can be a vector (instead of
a tuple) and d can be the diagonal position (instead of a tuple), defaulting to 0 (diagonal). Optionally, m and n
specify the size of the resulting sparse matrix.
sprand(m, n, p[, rng])
Create a random m by n sparse matrix, in which the probability of any element being nonzero is independently
given by p (and hence the mean density of nonzeros is also exactly p). Nonzero values are sampled from the
distribution specied by rng. The uniform distribution is used in case rng is not specied.
sprandn(m, n, p)
Create a randomm by n sparse matrix with the specied (independent) probability p of any entry being nonzero,
where nonzero values are sampled from the normal distribution.
sprandbool(m, n, p)
Create a random m by n sparse boolean matrix with the specied (independent) probability p of any entry being
true.
etree(A[, post ])
Compute the elimination tree of a symmetric sparse matrix A from triu(A) and, optionally, its post-ordering
permutation.
symperm(A, p)
Return the symmetric permutation of A, which is A[p,p]. A should be symmetric and sparse, where only the
upper triangular part of the matrix is stored. This algorithm ignores the lower triangular part of the matrix. Only
the upper triangular part of the result is returned as well.
nonzeros(A)
Return a vector of the structural nonzero values in sparse matrix A. This includes zeros that are explicitly
stored in the sparse matrix. The returned vector points directly to the internal nonzero storage of A, and any
modications to the returned vector will mutate A as well.
2.3 Linear Algebra
Linear algebra functions in Julia are largely implemented by calling functions from LAPACK. Sparse factorizations
call functions from SuiteSparse.
*
(A, B)
Matrix multiplication
\(A, B)
Matrix division using a polyalgorithm. For input matrices A and B, the result X is such that A
*
X == B when
A is square. The solver that is used depends upon the structure of A. A direct solver is used for upper- or lower
triangular A. For Hermitian A (equivalent to symmetric A for non-complex A) the BunchKaufman factorization
is used. Otherwise an LU factorization is used. For rectangular A the result is the minimum-norm least squares
solution computed by reducing A to bidiagonal form and solving the bidiagonal least squares problem. For
sparse, square A the LU factorization (from UMFPACK) is used.
dot(x, y)
(x, y)
Compute the dot product. For complex vectors, the rst vector is conjugated.
cross(x, y)
280 Chapter 2. The Julia Standard Library
Julia Language Documentation, Release 0.4.0-dev
(x, y)
Compute the cross product of two 3-vectors.
rref(A)
Compute the reduced row echelon form of the matrix A.
factorize(A)
Compute a convenient factorization (including LU, Cholesky, Bunch-Kaufman, Triangular) of A, based upon
the type of the input matrix. The return value can then be reused for efcient solving of multiple systems. For
example: A=factorize(A); x=A\\b; y=A\\C.
factorize!(A)
factorize! is the same as factorize(), but saves space by overwriting the input A, instead of creating a
copy.
lu(A) L, U, p
Compute the LU factorization of A, such that A[p,:] = L
*
U.
lufact(A[, pivot=true ]) F
Compute the LU factorization of A. The return type of F depends on the type of A. In most cases, if A is a subtype
S of AbstractMatrix with an element type T supporting +, -,
*
and / the return type is LU{T,S{T}}. If
pivoting is chosen (default) the element type should also support abs and <. When A is sparse and have
element of type Float32, Float64, Complex{Float32}, or Complex{Float64} the return type is
UmfpackLU. Some examples are shown in the table below.
Type of input A Type of output F Relationship between F and A
Matrix() LU F[:L]
*
F[:U] == A[F[:p], :]
Tridiagonal() LU{T,Tridiagonal{T}} N/A
SparseMatrixCSC()UmfpackLU F[:L]
*
F[:U] == Rs .
*
A[F[:p],
F[:q]]
The individual components of the factorization F can be accessed by indexing:
Compo-
nent
Description LU LU{T,Tridiagonal{T}} UmfpackLU
F[:L] L (lower triangular) part of
LU
x x
F[:U] U (upper triangular) part of
LU
x x
F[:p] (right) permutation Vector x x
F[:P] (right) permutation Matrix x
F[:q] left permutation Vector x
F[:Rs] Vector of scaling factors x
F[:(:)] (L,U,p,q,Rs)
components
x
Supported function LU LU{T,Tridiagonal{T}} UmfpackLU
/ x
\ x x x
cond x x
det x x x
size x x
lufact!(A) LU
lufact! is the same as lufact(), but saves space by overwriting the input A, instead of creating a copy.
For sparse A the nzval eld is not overwritten but the index elds, colptr and rowval are decremented in
place, converting from 1-based indices to 0-based indices.
2.3. Linear Algebra 281
Julia Language Documentation, Release 0.4.0-dev
chol(A[, LU]) F
Compute the Cholesky factorization of a symmetric positive denite matrix A and return the matrix F. If LU is
:L (Lower), A = L
*
L. If LU is :U (Upper), A = R
*
R.
cholfact(A, [LU,][pivot=false,][tol=-1.0]) Cholesky
Compute the Cholesky factorization of a dense symmetric positive (semi)denite matrix A and return either a
Cholesky if pivot=false or CholeskyPivoted if pivot=true. LU may be :L for using the lower
part or :U for the upper part. The default is to use :U. The triangular matrix can be obtained from the factor-
ization F with: F[:L] and F[:U]. The following functions are available for Cholesky objects: size, \,
inv, det. For CholeskyPivoted there is also dened a rank. If pivot=false a PosDefException
exception is thrown in case the matrix is not positive denite. The argument tol determines the tolerance for
determining the rank. For negative values, the tolerance is the machine precision.
cholfact(A[, ll ]) CholmodFactor
Compute the sparse Cholesky factorization of a sparse matrix A. If A is Hermitian its Cholesky factor is deter-
mined. If A is not Hermitian the Cholesky factor of A
*
A is determined. A ll-reducing permutation is used.
Methods for size, solve, \, findn_nzs, diag, det and logdet. One of the solve methods includes
an integer argument that can be used to solve systems involving parts of the factorization only. The optional
boolean argument, ll determines whether the factorization returned is of the A[p,p] = L
*
L form, where
L is lower triangular or A[p,p] = L
*
Diagonal(D)
*
L form where L is unit lower triangular and D is a
non-negative vector. The default is LDL.
cholfact!(A, [LU,][pivot=false,][tol=-1.0]) Cholesky
cholfact! is the same as cholfact(), but saves space by overwriting the input A, instead of creating a
copy.
ldltfact(A) LDLtFactorization
Compute a factorization of a positive denite matrix A such that A=L
*
Diagonal(d)
*
L where L is a unit
lower triangular matrix and d is a vector with non-negative elements.
qr(A, [pivot=false,][thin=true]) Q, R, [p]
Compute the (pivoted) QRfactorization of A such that either A = Q
*
R or A[:,p] = Q
*
R. Also see qrfact.
The default is to compute a thin factorization. Note that R is not extended with zeros when the full Q is requested.
qrfact(A[, pivot=false ]) F
Computes the QR factorization of A. The return type of F depends on the element type of A and whether pivoting
is specied (with pivot=true).
Return type eltype(A) pivot Relationship between F and A
QR not BlasFloat either A==F[:Q]
*
F[:R]
QRCompactWY BlasFloat false A==F[:Q]
*
F[:R]
QRPivoted BlasFloat true A[:,F[:p]]==F[:Q]
*
F[:R]
BlasFloat refers to any of: Float32, Float64, Complex64 or Complex128.
The individual components of the factorization F can be accessed by indexing:
Compo-
nent
Description QR QRCompactWY QRPivoted
F[:Q] Q (orthogonal/unitary) part
of QR
x
(QRPackedQ)
x
(QRCompactWYQ)
x
(QRPackedQ)
F[:R] R (upper right triangular)
part of QR
x x x
F[:p] pivot Vector x
F[:P] (pivot) permutation Matrix x
The following functions are available for the QR objects: size, \. When A is rectangular, \ will return a least
squares solution and if the solution is not unique, the one with smallest norm is returned.
282 Chapter 2. The Julia Standard Library
Julia Language Documentation, Release 0.4.0-dev
Multiplication with respect to either thin or full Q is allowed, i.e. both F[:Q]
*
F[:R] and F[:Q]
*
A are
supported. A Q matrix can be converted into a regular matrix with full() which has a named argument
thin.
Note: qrfact returns multiple types because LAPACKuses several representations that minimize the memory
storage requirements of products of Householder elementary reectors, so that the Q and R matrices can be stored
compactly rather as two separate dense matrices.
The data contained in QR or QRPivoted can be used to construct the QRPackedQ type, which is a compact
representation of the rotation matrix:
Q =
min(m,n)
i=1
(I
i
v
i
v
T
i
)
where
i
is the scale factor and v
i
is the projection vector associated with the i
th
Householder elementary
reector.
The data contained in QRCompactWY can be used to construct the QRCompactWYQ type, which is a compact
representation of the rotation matrix
Q = I + Y TY
T
where Y is m r lower trapezoidal and T is r r upper triangular. The compact WY representation
[Schreiber1989] is not to be confused with the older, WY representation [Bischof1987]. (The LAPACK docu-
mentation uses V in lieu of Y.)
qrfact!(A[, pivot=false ])
qrfact! is the same as qrfact(), but saves space by overwriting the input A, instead of creating a copy.
bkfact(A) BunchKaufman
Compute the Bunch-Kaufman [Bunch1977] factorization of a real symmetric or complex Hermitian matrix A
and return a BunchKaufman object. The following functions are available for BunchKaufman objects:
size, \, inv, issym, ishermitian.
bkfact!(A) BunchKaufman
bkfact! is the same as bkfact(), but saves space by overwriting the input A, instead of creating a copy.
sqrtm(A)
Compute the matrix square root of A. If B = sqrtm(A), then B
*
B == A within roundoff error.
sqrtm uses a polyalgorithm, computing the matrix square root using Schur factorizations (schurfact())
unless it detects the matrix to be Hermitian or real symmetric, in which case it computes the matrix square root
from an eigendecomposition (eigfact()). In the latter situation for positive denite matrices, the matrix
square root has Real elements, otherwise it has Complex elements.
eig(A,[irange,][vl,][vu,][permute=true,][scale=true]) D, V
Compute eigenvalues and eigenvectors of A. See eigfact() for details on the balance keyword argument.
julia> eig([1.0 0.0 0.0; 0.0 3.0 0.0; 0.0 0.0 18.0])
([1.0,3.0,18.0],
3x3 Array{Float64,2}:
1.0 0.0 0.0
0.0 1.0 0.0
0.0 0.0 1.0)
2.3. Linear Algebra 283
Julia Language Documentation, Release 0.4.0-dev
eig is a wrapper around eigfact(), extracting all parts of the factorization to a tuple; where possible, using
eigfact() is recommended.
eig(A, B) D, V
Computes generalized eigenvalues and vectors of A with respect to B.
eig is a wrapper around eigfact(), extracting all parts of the factorization to a tuple; where possible, using
eigfact() is recommended.
eigvals(A,[irange,][vl,][vu])
Returns the eigenvalues of A. If A is Symmetric(), Hermitian() or SymTridiagonal(), it is possible
to calculate only a subset of the eigenvalues by specifying either a UnitRange() irange covering indices
of the sorted eigenvalues, or a pair vl and vu for the lower and upper boundaries of the eigenvalues.
For general non-symmetric matrices it is possible to specify how the matrix is balanced before the eigenvec-
tor calculation. The option permute=true permutes the matrix to become closer to upper triangular, and
scale=true scales the matrix by its diagonal elements to make rows and columns more equal in norm. The
default is true for both options.
eigmax(A)
Returns the largest eigenvalue of A.
eigmin(A)
Returns the smallest eigenvalue of A.
eigvecs(A, [eigvals,][permute=true,][scale=true])
Returns the eigenvectors of A. The permute and scale keywords are the same as for eigfact().
For SymTridiagonal() matrices, if the optional vector of eigenvalues eigvals is specied, returns the
specic corresponding eigenvectors.
eigfact(A,[il,][iu,][vl,][vu,][permute=true,][scale=true])
Compute the eigenvalue decomposition of A and return an Eigen object. If F is the factorization object, the
eigenvalues can be accessed with F[:values] and the eigenvectors with F[:vectors]. The following
functions are available for Eigen objects: inv, det.
If A is Symmetric, Hermitian or SymTridiagonal, it is possible to calculate only a subset of the
eigenvalues by specifying either a UnitRange irange covering indices of the sorted eigenvalues or a pair vl
and vu for the lower and upper boundaries of the eigenvalues.
For general non-symmetric matrices it is possible to specify how the matrix is balanced before the eigenvec-
tor calculation. The option permute=true permutes the matrix to become closer to upper triangular, and
scale=true scales the matrix by its diagonal elements to make rows and columns more equal in norm. The
default is true for both options.
eigfact(A, B)
Compute the generalized eigenvalue decomposition of A and B and return an GeneralizedEigen object.
If F is the factorization object, the eigenvalues can be accessed with F[:values] and the eigenvectors with
F[:vectors].
eigfact!(A[, B])
eigfact! is the same as eigfact(), but saves space by overwriting the input A (and B), instead of creating
a copy.
hessfact(A)
Compute the Hessenberg decomposition of A and return a Hessenberg object. If F is the factorization object,
the unitary matrix can be accessed with F[:Q] and the Hessenberg matrix with F[:H]. When Q is extracted,
the resulting type is the HessenbergQ object, and may be converted to a regular matrix with full().
hessfact!(A)
hessfact! is the same as hessfact(), but saves space by overwriting the input A, instead of creating a
284 Chapter 2. The Julia Standard Library
Julia Language Documentation, Release 0.4.0-dev
copy.
schurfact(A) Schur
Computes the Schur factorization of the matrix A. The (quasi) triangular Schur factor can be obtained from
the Schur object F with either F[:Schur] or F[:T] and the unitary/orthogonal Schur vectors can be ob-
tained with F[:vectors] or F[:Z] such that A=F[:vectors]
*
F[:Schur]
*
F[:vectors]. The
eigenvalues of A can be obtained with F[:values].
schurfact!(A)
Computer the Schur factorization of A, overwriting A in the process. See schurfact()
schur(A) Schur[:T], Schur[:Z], Schur[:values]
See schurfact()
schurfact(A, B) GeneralizedSchur
Computes the Generalized Schur (or QZ) factorization of the matrices A and B. The (quasi) triangular Schur
factors can be obtained from the Schur object F with F[:S] and F[:T], the left unitary/orthogonal
Schur vectors can be obtained with F[:left] or F[:Q] and the right unitary/orthogonal Schur vec-
tors can be obtained with F[:right] or F[:Z] such that A=F[:left]
*
F[:S]
*
F[:right] and
B=F[:left]
*
F[:T]
*
F[:right]. The generalized eigenvalues of A and B can be obtained with
F[:alpha]./F[:beta].
schur(A, B) GeneralizedSchur[:S], GeneralizedSchur[:T], GeneralizedSchur[:Q], GeneralizedSchur[:Z]
See schurfact()
svdfact(A[, thin=true ]) SVD
Compute the Singular Value Decomposition (SVD) of A and return an SVD object. U, S, V and Vt can be ob-
tained from the factorization F with F[:U], F[:S], F[:V] and F[:Vt], such that A = U
*
diagm(S)
*
Vt.
If thin is true, an economy mode decomposition is returned. The algorithm produces Vt and hence Vt is
more efcient to extract than V. The default is to produce a thin decomposition.
svdfact!(A[, thin=true ]) SVD
svdfact! is the same as svdfact(), but saves space by overwriting the input A, instead of creating a copy.
If thin is true, an economy mode decomposition is returned. The default is to produce a thin decomposition.
svd(A[, thin=true ]) U, S, V
Wrapper around svdfact extracting all parts the factorization to a tuple. Direct use of svdfact is
therefore generally more efcient. Computes the SVD of A, returning U, vector S, and V such that A ==
U
*
diagm(S)
*
V. If thin is true, an economy mode decomposition is returned. The default is to produce
a thin decomposition.
svdvals(A)
Returns the singular values of A.
svdvals!(A)
Returns the singular values of A, while saving space by overwriting the input.
svdfact(A, B) GeneralizedSVD
Compute the generalized SVD of A and B, returning a GeneralizedSVD Factorization object F, such that A
= F[:U]
*
F[:D1]
*
F[:R0]
*
F[:Q] and B = F[:V]
*
F[:D2]
*
F[:R0]
*
F[:Q].
svd(A, B) U, V, Q, D1, D2, R0
Wrapper around svdfact extracting all parts the factorization to a tuple. Direct use of svdfact is therefore
generally more efcient. The function returns the generalized SVD of A and B, returning U, V, Q, D1, D2, and
R0 such that A = U
*
D1
*
R0
*
Q and B = V
*
D2
*
R0
*
Q.
svdvals(A, B)
Return only the singular values from the generalized singular value decomposition of A and B.
triu(M)
Upper triangle of a matrix.
2.3. Linear Algebra 285
Julia Language Documentation, Release 0.4.0-dev
triu!(M)
Upper triangle of a matrix, overwriting M in the process.
tril(M)
Lower triangle of a matrix.
tril!(M)
Lower triangle of a matrix, overwriting M in the process.
diagind(M[, k ])
A Range giving the indices of the k-th diagonal of the matrix M.
diag(M[, k ])
The k-th diagonal of a matrix, as a vector. Use diagm to construct a diagonal matrix.
diagm(v[, k ])
Construct a diagonal matrix and place v on the k-th diagonal.
scale(A, b)
scale(b, A)
Scale an array A by a scalar b, returning a new array.
If A is a matrix and b is a vector, then scale(A,b) scales each column i of A by b[i] (similar to
A
*
diagm(b)), while scale(b,A) scales each row i of A by b[i] (similar to diagm(b)
*
A), returning a
new array.
Note: for large A, scale can be much faster than A .
*
b or b .
*
A, due to the use of BLAS.
scale!(A, b)
scale!(b, A)
Scale an array A by a scalar b, similar to scale() but overwriting A in-place.
If A is a matrix and b is a vector, then scale!(A,b) scales each column i of A by b[i] (similar to
A
*
diagm(b)), while scale!(b,A) scales each row i of A by b[i] (similar to diagm(b)
*
A), again
operating in-place on A.
Tridiagonal(dl, d, du)
Construct a tridiagonal matrix from the lower diagonal, diagonal, and upper diagonal, respectively. The result
is of type Tridiagonal and provides efcient specialized linear solvers, but may be converted into a regular
matrix with full().
Bidiagonal(dv, ev, isupper)
Constructs an upper (isupper=true) or lower (isupper=false) bidiagonal matrix using the given diag-
onal (dv) and off-diagonal (ev) vectors. The result is of type Bidiagonal and provides efcient specialized
linear solvers, but may be converted into a regular matrix with full().
SymTridiagonal(d, du)
Construct a real symmetric tridiagonal matrix from the diagonal and upper diagonal, respectively. The result is
of type SymTridiagonal and provides efcient specialized eigensolvers, but may be converted into a regular
matrix with full().
Woodbury(A, U, C, V)
Construct a matrix in a form suitable for applying the Woodbury matrix identity.
rank(M)
Compute the rank of a matrix.
norm(A[, p])
Compute the p-norm of a vector or the operator norm of a matrix A, defaulting to the p=2-norm.
286 Chapter 2. The Julia Standard Library
Julia Language Documentation, Release 0.4.0-dev
For vectors, p can assume any numeric value (even though not all values produce a mathematically valid vector
norm). In particular, norm(A, Inf) returns the largest value in abs(A), whereas norm(A, -Inf) returns
the smallest.
For matrices, valid values of p are 1, 2, or Inf. (Note that for sparse matrices, p=2 is currently not imple-
mented.) Use vecnorm() to compute the Frobenius norm.
vecnorm(A[, p])
For any iterable container A (including arrays of any dimension) of numbers, compute the p-norm (defaulting
to p=2) as if A were a vector of the corresponding length.
For example, if A is a matrix and p=2, then this is equivalent to the Frobenius norm.
cond(M[, p])
Condition number of the matrix M, computed using the operator p-norm. Valid values for p are 1, 2 (default),
or Inf.
condskeel(M[, x, p])
S
(M, p) =
|M|
M
1
S
(M, x, p) =
|M|
M
1
|x|
p
Skeel condition number
S
of the matrix M, optionally with respect to the vector x, as computed using the
operator p-norm. p is Inf by default, if not provided. Valid values for p are 1, 2, or Inf.
This quantity is also known in the literature as the Bauer condition number, relative condition number, or com-
ponentwise relative condition number.
trace(M)
Matrix trace
det(M)
Matrix determinant
logdet(M)
Log of matrix determinant. Equivalent to log(det(M)), but may provide increased accuracy and/or speed.
inv(M)
Matrix inverse
pinv(M)
Moore-Penrose pseudoinverse
null(M)
Basis for nullspace of M.
repmat(A, n, m)
Construct a matrix by repeating the given matrix n times in dimension 1 and m times in dimension 2.
repeat(A, inner = Int[], outer = Int[])
Construct an array by repeating the entries of A. The i-th element of inner species the number of times that
the individual entries of the i-th dimension of A should be repeated. The i-th element of outer species the
number of times that a slice along the i-th dimension of A should be repeated.
kron(A, B)
Kronecker tensor product of two vectors or two matrices.
blkdiag(A...)
Concatenate matrices block-diagonally. Currently only implemented for sparse matrices.
linreg(x, y) [a; b]
Linear Regression. Returns a and b such that a+b
*
x is the closest line to the given points (x,y). In other
words, this function determines parameters [a, b] that minimize the squared error between y and a+b
*
x.
2.3. Linear Algebra 287
Julia Language Documentation, Release 0.4.0-dev
Example:
using PyPlot;
x = float([1:12])
y = [5.5; 6.3; 7.6; 8.8; 10.9; 11.79; 13.48; 15.02; 17.77; 20.81; 22.0; 22.99]
a, b = linreg(x,y) # Linear regression
plot(x, y, "o") # Plot (x,y) points
plot(x, [a+b
*
i for i in x]) # Plot the line determined by the linear regression
linreg(x, y, w)
Weighted least-squares linear regression.
expm(A)
Matrix exponential.
lyap(A, C)
Computes the solution X to the continuous Lyapunov equation AX + XA + C = 0, where no eigenvalue of
A has a zero real part and no two eigenvalues are negative complex conjugates of each other.
sylvester(A, B, C)
Computes the solution X to the Sylvester equation AX + XB + C = 0, where A, B and C have compatible
dimensions and A and -B have no eigenvalues with equal real part.
issym(A) Bool
Test whether a matrix is symmetric.
isposdef(A) Bool
Test whether a matrix is positive denite.
isposdef!(A) Bool
Test whether a matrix is positive denite, overwriting A in the processes.
istril(A) Bool
Test whether a matrix is lower triangular.
istriu(A) Bool
Test whether a matrix is upper triangular.
ishermitian(A) Bool
Test whether a matrix is Hermitian.
transpose(A)
The transposition operator (.).
ctranspose(A)
The conjugate transposition operator ().
eigs(A[, B], ; nev=6, which=LM, tol=0.0, maxiter=1000, sigma=nothing, ritzvec=true, v0=zeros((0, )))
-> (d[, v ], nconv, niter, nmult, resid)
eigs computes eigenvalues d of A using Lanczos or Arnoldi iterations for real symmetric or general nonsymmetric matrices respectively. If B is provided, the generalized eigen-problem is solved. The following keyword arguments are supported:
nev: Number of eigenvalues
ncv: Number of Krylov vectors used in the computation; should satisfy nev+1 <= ncv <= n
for real symmetric problems and nev+2 <= ncv <= n for other problems; default is ncv =
max(20,2
*
nev+1).
which: type of eigenvalues to compute. See the note below.
288 Chapter 2. The Julia Standard Library
Julia Language Documentation, Release 0.4.0-dev
which type of eigenvalues
:LM eigenvalues of largest magnitude (default)
:SM eigenvalues of smallest magnitude
:LR eigenvalues of largest real part
:SR eigenvalues of smallest real part
:LI eigenvalues of largest imaginary part (nonsymmetric or complex A only)
:SI eigenvalues of smallest imaginary part (nonsymmetric or complex A only)
:BE compute half of the eigenvalues from each end of the spectrum, biased in favor of the
high end. (real symmetric A only)
tol: tolerance (tol 0.0 defaults to DLAMCH(EPS))
maxiter: Maximum number of iterations (default = 300)
sigma: Species the level shift used in inverse iteration. If nothing (default), defaults to ordinary
(forward) iterations. Otherwise, nd eigenvalues close to sigma using shift and invert iterations.
ritzvec: Returns the Ritz vectors v (eigenvectors) if true
v0: starting vector from which to start the iterations
eigs returns the nev requested eigenvalues in d, the corresponding Ritz vectors v (only if ritzvec=true),
the number of converged eigenvalues nconv, the number of iterations niter and the number of matrix vector
multiplications nmult, as well as the nal residual vector resid.
Note: The sigma and which keywords interact: the description of eigenvalues searched for by which do
_not_ necessarily refer to the eigenvalues of A, but rather the linear operator constructed by the specication of
the iteration mode implied by sigma.
sigma iteration mode which refers to eigenvalues of
nothing ordinary (forward) A
real or complex inverse with level shift sigma (AI)
1
peakflops(n; parallel=false)
peakflops computes the peak op rate of the computer by using double precision
Base.LinAlg.BLAS.gemm!(). By default, if no arguments are specied, it multiplies a matrix of
size n x n, where n = 2000. If the underlying BLAS is using multiple threads, higher op rates are
realized. The number of BLAS threads can be set with blas_set_num_threads(n).
If the keyword argument parallel is set to true, peakflops is run in parallel on all the worker processors.
The op rate of the entire parallel computer is returned. When running in parallel, only 1 BLAS thread is used.
The argument n still refers to the size of the problem that is solved on each processor.
2.4 BLAS Functions
This module provides wrappers for some of the BLAS functions for linear algebra. Those BLAS functions that
overwrite one of the input arrays have names ending in !.
Usually a function has 4 methods dened, one each for Float64, Float32, Complex128 and Complex64
arrays.
dot(n, X, incx, Y, incy)
Dot product of two vectors consisting of n elements of array X with stride incx and n elements of array Y with
stride incy.
dotu(n, X, incx, Y, incy)
Dot function for two complex vectors.
2.4. BLAS Functions 289
Julia Language Documentation, Release 0.4.0-dev
dotc(n, X, incx, U, incy)
Dot function for two complex vectors conjugating the rst vector.
blascopy!(n, X, incx, Y, incy)
Copy n elements of array X with stride incx to array Y with stride incy. Returns Y.
nrm2(n, X, incx)
2-norm of a vector consisting of n elements of array X with stride incx.
asum(n, X, incx)
sum of the absolute values of the rst n elements of array X with stride incx.
axpy!(n, a, X, incx, Y, incy)
Overwrite Y with a
*
X + Y. Returns Y.
scal!(n, a, X, incx)
Overwrite X with a
*
X. Returns X.
scal(n, a, X, incx)
Returns a
*
X.
syrk!(uplo, trans, alpha, A, beta, C)
Rank-k update of the symmetric matrix C as alpha
*
A
*
A. + beta
*
C or alpha
*
A.
*
A + beta
*
C
according to whether trans is N or T. When uplo is U the upper triangle of C is updated (L for lower
triangle). Returns C.
syrk(uplo, trans, alpha, A)
Returns either the upper triangle or the lower triangle, according to uplo (U or L), of alpha
*
A
*
A. or
alpha
*
A.
*
A, according to trans (N or T).
herk!(uplo, trans, alpha, A, beta, C)
Methods for complex arrays only. Rank-k update of the Hermitian matrix C as alpha
*
A
*
A + beta
*
C or
alpha
*
A
*
A + beta
*
C according to whether trans is N or T. When uplo is U the upper triangle
of C is updated (L for lower triangle). Returns C.
herk(uplo, trans, alpha, A)
Methods for complex arrays only. Returns either the upper triangle or the lower triangle, according to uplo
(U or L), of alpha
*
A
*
A or alpha
*
A
*
A, according to trans (N or T).
gbmv!(trans, m, kl, ku, alpha, A, x, beta, y)
Update vector y as alpha
*
A
*
x + beta
*
y or alpha
*
A
*
x + beta
*
y according to trans (N or T).
The matrix A is a general band matrix of dimension m by size(A,2) with kl sub-diagonals and ku super-
diagonals. Returns the updated y.
gbmv(trans, m, kl, ku, alpha, A, x, beta, y)
Returns alpha
*
A
*
x or alpha
*
A
*
x according to trans (N or T). The matrix A is a general band matrix
of dimension m by size(A,2) with kl sub-diagonals and ku super-diagonals.
sbmv!(uplo, k, alpha, A, x, beta, y)
Update vector y as alpha
*
A
*
x + beta
*
y where A is a a symmetric band matrix of order size(A,2) with
k super-diagonals stored in the argument A. The storage layout for A is described the reference BLAS module,
level-2 BLAS at http://www.netlib.org/lapack/explore-html/.
Returns the updated y.
sbmv(uplo, k, alpha, A, x)
Returns alpha
*
A
*
x where A is a symmetric band matrix of order size(A,2) with k super-diagonals stored
in the argument A.
sbmv(uplo, k, A, x)
Returns A
*
x where A is a symmetric band matrix of order size(A,2) with k super-diagonals stored in the
argument A.
290 Chapter 2. The Julia Standard Library
Julia Language Documentation, Release 0.4.0-dev
gemm!(tA, tB, alpha, A, B, beta, C)
Update C as alpha
*
A
*
B + beta
*
C or the other three variants according to tA (transpose A) and tB. Returns
the updated C.
gemm(tA, tB, alpha, A, B)
Returns alpha
*
A
*
B or the other three variants according to tA (transpose A) and tB.
gemm(tA, tB, A, B)
Returns A
*
B or the other three variants according to tA (transpose A) and tB.
gemv!(tA, alpha, A, x, beta, y)
Update the vector y as alpha
*
A
*
x + beta
*
x or alpha
*
Ax + beta
*
x according to tA (transpose A).
Returns the updated y.
gemv(tA, alpha, A, x)
Returns alpha
*
A
*
x or alpha
*
Ax according to tA (transpose A).
gemv(tA, A, x)
Returns A
*
x or Ax according to tA (transpose A).
symm!(side, ul, alpha, A, B, beta, C)
Update C as alpha
*
A
*
B + beta
*
C or alpha
*
B
*
A + beta
*
C according to side. A is assumed to be
symmetric. Only the ul triangle of A is used. Returns the updated C.
symm(side, ul, alpha, A, B)
Returns alpha
*
A
*
B or alpha
*
B
*
A according to side. A is assumed to be symmetric. Only the ul triangle
of A is used.
symm(side, ul, A, B)
Returns A
*
B or B
*
A according to side. A is assumed to be symmetric. Only the ul triangle of A is used.
symm(tA, tB, alpha, A, B)
Returns alpha
*
A
*
B or the other three variants according to tA (transpose A) and tB.
symv!(ul, alpha, A, x, beta, y)
Update the vector y as alpha
*
A
*
y + beta
*
y. A is assumed to be symmetric. Only the ul triangle of A is
used. Returns the updated y.
symv(ul, alpha, A, x)
Returns alpha
*
A
*
x. A is assumed to be symmetric. Only the ul triangle of A is used.
symv(ul, A, x)
Returns A
*
x. A is assumed to be symmetric. Only the ul triangle of A is used.
trmm!(side, ul, tA, dA, alpha, A, B)
Update B as alpha
*
A
*
B or one of the other three variants determined by side (A on left or right) and tA
(transpose A). Only the ul triangle of A is used. dA indicates if A is unit-triangular (the diagonal is assumed to
be all ones). Returns the updated B.
trmm(side, ul, tA, dA, alpha, A, B)
Returns alpha
*
A
*
B or one of the other three variants determined by side (A on left or right) and tA (trans-
pose A). Only the ul triangle of A is used. dA indicates if A is unit-triangular (the diagonal is assumed to be all
ones).
trsm!(side, ul, tA, dA, alpha, A, B)
Overwrite B with the solution to A
*
X = alpha
*
B or one of the other three variants determined by side (A
on left or right of X) and tA (transpose A). Only the ul triangle of A is used. dA indicates if A is unit-triangular
(the diagonal is assumed to be all ones). Returns the updated B.
trsm(side, ul, tA, dA, alpha, A, B)
Returns the solution to A
*
X = alpha
*
B or one of the other three variants determined by side (A on left
2.4. BLAS Functions 291
Julia Language Documentation, Release 0.4.0-dev
or right of X) and tA (transpose A). Only the ul triangle of A is used. dA indicates if A is unit-triangular (the
diagonal is assumed to be all ones).
trmv!(side, ul, tA, dA, alpha, A, b)
Update b as alpha
*
A
*
b or one of the other three variants determined by side (A on left or right) and tA
(transpose A). Only the ul triangle of A is used. dA indicates if A is unit-triangular (the diagonal is assumed to
be all ones). Returns the updated b.
trmv(side, ul, tA, dA, alpha, A, b)
Returns alpha
*
A
*
b or one of the other three variants determined by side (A on left or right) and tA (trans-
pose A). Only the ul triangle of A is used. dA indicates if A is unit-triangular (the diagonal is assumed to be all
ones).
trsv!(ul, tA, dA, A, b)
Overwrite b with the solution to A
*
x = b or one of the other two variants determined by tA (transpose A) and
ul (triangle of A used). dA indicates if A is unit-triangular (the diagonal is assumed to be all ones). Returns the
updated b.
trsv(ul, tA, dA, A, b)
Returns the solution to A
*
x = b or one of the other two variants determined by tA (transpose A) and ul
(triangle of A is used.) dA indicates if A is unit-triangular (the diagonal is assumed to be all ones).
blas_set_num_threads(n)
Set the number of threads the BLAS library should use.
2.5 Constants
OS_NAME
A symbol representing the name of the operating system. Possible values are :Linux, :Darwin (OS X), or
:Windows.
ARGS
An array of the command line arguments passed to Julia, as strings.
C_NULL
The C null pointer constant, sometimes used when calling external code.
CPU_CORES
The number of CPU cores in the system.
WORD_SIZE
Standard word size on the current machine, in bits.
VERSION
An object describing which version of Julia is in use.
LOAD_PATH
An array of paths (as strings) where the require function looks for code.
2.6 Filesystem
isblockdev(path) Bool
Returns true if path is a block device, false otherwise.
ischardev(path) Bool
Returns true if path is a character device, false otherwise.
292 Chapter 2. The Julia Standard Library
Julia Language Documentation, Release 0.4.0-dev
isdir(path) Bool
Returns true if path is a directory, false otherwise.
isexecutable(path) Bool
Returns true if the current user has permission to execute path, false otherwise.
isfifo(path) Bool
Returns true if path is a FIFO, false otherwise.
isfile(path) Bool
Returns true if path is a regular le, false otherwise.
islink(path) Bool
Returns true if path is a symbolic link, false otherwise.
ispath(path) Bool
Returns true if path is a valid lesystem path, false otherwise.
isreadable(path) Bool
Returns true if the current user has permission to read path, false otherwise.
issetgid(path) Bool
Returns true if path has the setgid ag set, false otherwise.
issetuid(path) Bool
Returns true if path has the setuid ag set, false otherwise.
issocket(path) Bool
Returns true if path is a socket, false otherwise.
issticky(path) Bool
Returns true if path has the sticky bit set, false otherwise.
iswritable(path) Bool
Returns true if the current user has permission to write to path, false otherwise.
homedir() String
Return the current users home directory.
dirname(path::String) String
Get the directory part of a path.
basename(path::String) String
Get the le name part of a path.
@__FILE__() String
@__FILE__ expands to a string with the absolute path and le name of the script being run. Returns nothing
if run from a REPL or an empty string if evaluated by julia -e <expr>.
isabspath(path::String) Bool
Determines whether a path is absolute (begins at the root directory).
isdirpath(path::String) Bool
Determines whether a path refers to a directory (for example, ends with a path separator).
joinpath(parts...) String
Join path components into a full path. If some argument is an absolute path, then prior components are dropped.
abspath(path::String) String
Convert a path to an absolute path by adding the current directory if necessary.
normpath(path::String) String
Normalize a path, removing . and .. entries.
2.6. Filesystem 293
Julia Language Documentation, Release 0.4.0-dev
realpath(path::String) String
Canonicalize a path by expanding symbolic links and removing . and .. entries.
expanduser(path::String) String
On Unix systems, replace a tilde character at the start of a path with the current users home directory.
splitdir(path::String) -> (String, String)
Split a path into a tuple of the directory name and le name.
splitdrive(path::String) -> (String, String)
On Windows, split a path into the drive letter part and the path part. On Unix systems, the rst component is
always the empty string.
splitext(path::String) -> (String, String)
If the last component of a path contains a dot, split the path into everything before the dot and everything
including and after the dot. Otherwise, return a tuple of the argument unmodied and the empty string.
tempname()
Generate a unique temporary lename.
tempdir()
Obtain the path of a temporary directory.
mktemp()
Returns (path, io), where path is the path of a new temporary le and io is an open le object for this
path.
mktempdir()
Create a temporary directory and return its path.
2.7 Punctuation
Extended documentation for mathematical symbols & functions is here.
symbol meaning
@m invoke macro m; followed by space-separated expressions
! prex not operator
a!( ) at the end of a function name, ! indicates that a function modies its argument(s)
# begin single line comment
#= begin multi-line comment (these are nestable)
=# end multi-line comment
$ xor operator, string and expression interpolation
% remainder operator
^ exponent operator
& bitwise and
*
multiply, or matrix multiply
() the empty tuple
~ bitwise not operator
\ backslash operator
complex transpose operator A
H
a[] array indexing
[,] vertical concatenation
[;] also vertical concatenation
[ ] with space-separated expressions, horizontal concatenation
T{ } parametric type instantiation
Continued on next page
294 Chapter 2. The Julia Standard Library
Julia Language Documentation, Release 0.4.0-dev
Table 2.1 continued from previous page
symbol meaning
{ } construct a cell array
; statement separator
, separate function arguments or tuple components
? 3-argument conditional operator (conditional ? if_true : if_false)
"" delimit string literals
delimit character literals
delimit external process (command) specications
... splice arguments into a function call or declare a varargs function or type
. access named elds in objects or names inside modules, also prexes elementwise operators
a:b range a, a+1, a+2, ..., b
a:s:b range a, a+s, a+2s, ..., b
: index an entire dimension (1:end)
:: type annotation, depending on context
:( ) quoted expression
:a symbol a
2.8 Sorting and Related Functions
Julia has an extensive, exible API for sorting and interacting with already-sorted arrays of values. By default, Julia
picks reasonable algorithms and sorts in standard ascending order:
julia> sort([2,3,1])
3-element Array{Int64,1}:
1
2
3
You can easily sort in reverse order as well:
julia> sort([2,3,1], rev=true)
3-element Array{Int64,1}:
3
2
1
To sort an array in-place, use the bang version of the sort function:
julia> a = [2,3,1];
julia> sort!(a);
julia> a
3-element Array{Int64,1}:
1
2
3
Instead of directly sorting an array, you can compute a permutation of the arrays indices that puts the array into sorted
order:
2.8. Sorting and Related Functions 295
Julia Language Documentation, Release 0.4.0-dev
julia> v = randn(5)
5-element Array{Float64,1}:
0.297288
0.382396
-0.597634
-0.0104452
-0.839027
julia> p = sortperm(v)
5-element Array{Int64,1}:
5
3
4
1
2
julia> v[p]
5-element Array{Float64,1}:
-0.839027
-0.597634
-0.0104452
0.297288
0.382396
Arrays can easily be sorted according to an arbitrary transformation of their values:
julia> sort(v, by=abs)
5-element Array{Float64,1}:
-0.0104452
0.297288
0.382396
-0.597634
-0.839027
Or in reverse order by a transformation:
julia> sort(v, by=abs, rev=true)
5-element Array{Float64,1}:
-0.839027
-0.597634
0.382396
0.297288
-0.0104452
If needed, the sorting algorithm can be chosen:
julia> sort(v, alg=InsertionSort)
5-element Array{Float64,1}:
-0.839027
-0.597634
-0.0104452
0.297288
0.382396
All the sorting and order related functions rely on a less than relation dening a total order on the values to be
manipulated. The isless function is invoked by default, but the relation can be specied via the lt keyword.
296 Chapter 2. The Julia Standard Library
Julia Language Documentation, Release 0.4.0-dev
2.8.1 Sorting Functions
sort!(v, [alg=<algorithm>,] [by=<transform>,] [lt=<comparison>,] [rev=false])
Sort the vector v in place. QuickSort is used by default for numeric arrays while MergeSort is used for
other arrays. You can specify an algorithm to use via the alg keyword (see Sorting Algorithms for available
algorithms). The by keyword lets you provide a function that will be applied to each element before comparison;
the lt keyword allows providing a custom less than function; use rev=true to reverse the sorting order.
These options are independent and can be used together in all possible combinations: if both by and lt are
specied, the lt function is applied to the result of the by function; rev=true reverses whatever ordering
specied via the by and lt keywords.
sort(v, [alg=<algorithm>,] [by=<transform>,] [lt=<comparison>,] [rev=false])
Variant of sort! that returns a sorted copy of v leaving v itself unmodied.
sort(A, dim, [alg=<algorithm>,] [by=<transform>,] [lt=<comparison>,] [rev=false])
Sort a multidimensional array A along the given dimension.
sortperm(v, [alg=<algorithm>,] [by=<transform>,] [lt=<comparison>,] [rev=false])
Return a permutation vector of indices of v that puts it in sorted order. Specify alg to choose a particular
sorting algorithm (see Sorting Algorithms). MergeSort is used by default, and since it is stable, the resulting
permutation will be the lexicographically rst one that puts the input array into sorted order i.e. indices of
equal elements appear in ascending order. If you choose a non-stable sorting algorithm such as QuickSort,
a different permutation that puts the array into order may be returned. The order is specied using the same
keywords as sort!.
sortrows(A, [alg=<algorithm>,] [by=<transform>,] [lt=<comparison>,] [rev=false])
Sort the rows of matrix A lexicographically.
sortcols(A, [alg=<algorithm>,] [by=<transform>,] [lt=<comparison>,] [rev=false])
Sort the columns of matrix A lexicographically.
2.8.2 Order-Related Functions
issorted(v, [by=<transform>,] [lt=<comparison>,] [rev=false])
Test whether a vector is in sorted order. The by, lt and rev keywords modify what order is considered to be
sorted just as they do for sort.
searchsorted(a, x, [by=<transform>,] [lt=<comparison>,] [rev=false])
Returns the range of indices of a which compare as equal to x according to the order specied by the by, lt and
rev keywords, assuming that a is already sorted in that order. Returns an empty range located at the insertion
point if a does not contain values equal to x.
searchsortedfirst(a, x, [by=<transform>,] [lt=<comparison>,] [rev=false])
Returns the index of the rst value in a greater than or equal to x, according to the specied order. Returns
length(a)+1 if x is greater than all values in a.
searchsortedlast(a, x, [by=<transform>,] [lt=<comparison>,] [rev=false])
Returns the index of the last value in a less than or equal to x, according to the specied order. Returns 0 if x
is less than all values in a.
select!(v, k, [by=<transform>,] [lt=<comparison>,] [rev=false])
Partially sort the vector v in place, according to the order specied by by, lt and rev so that the value at index
k (or range of adjacent values if k is a range) occurs at the position where it would appear if the array were fully
sorted via a non-stable algorithm. If k is a single index, that value is returned; if k is a range, an array of values
at those indices is returned. Note that select! does not fully sort the input array.
2.8. Sorting and Related Functions 297
Julia Language Documentation, Release 0.4.0-dev
select(v, k, [by=<transform>,] [lt=<comparison>,] [rev=false])
Variant of select! which copies v before partially sorting it, thereby returning the same thing as select!
but leaving v unmodied.
2.8.3 Sorting Algorithms
There are currently three sorting algorithms available in base Julia:
InsertionSort
QuickSort
MergeSort
InsertionSort is an O(n^2) stable sorting algorithm. It is efcient for very small n, and is used internally by
QuickSort.
QuickSort is an O(n log n) sorting algorithm which is in-place, very fast, but not stable i.e. elements which
are considered equal will not remain in the same order in which they originally appeared in the array to be sorted.
QuickSort is the default algorithm for numeric values, including integers and oats.
MergeSort is an O(n log n) stable sorting algorithm but is not in-place it requires a temporary array of half the
size of the input array and is typically not quite as fast as QuickSort. It is the default algorithm for non-numeric
data.
The default sorting algorithms are chosen on the basis that they are fast and stable, or appear to be so. For numeric
types indeed, QuickSort is selected as it is faster and indistinguishable in this case from a stable sort (unless the
array records its mutations in some way). The stability property comes at a non-negligible cost, so if you dont need
it, you may want to explicitly specify your preferred algorithm, e.g. sort!(v, alg=QuickSort).
The mechanism by which Julia picks default sorting algorithms is implemented via the Base.Sort.defalg func-
tion. It allows a particular algorithm to be registered as the default in all sorting functions for specic arrays. For
example, here are the two default methods from sort.jl:
defalg(v::AbstractArray) = MergeSort
defalg{T<:Number}(v::AbstractArray{T}) = QuickSort
As for numeric arrays, choosing a non-stable default algorithm for array types for which the notion of a stable sort is
meaningless (i.e. when two values comparing equal can not be distinguished) may make sense.
2.9 Package Manager Functions
All package manager functions are dened in the Pkg module. None of the Pkg modules functions are exported; to
use them, youll need to prex each function call with an explicit Pkg., e.g. Pkg.status() or Pkg.dir().
dir() String
Returns the absolute path of the package directory. This defaults to joinpath(homedir(),".julia")
on all platforms (i.e. ~/.julia in UNIX shell syntax). If the JULIA_PKGDIR environment variable is set,
that path is used instead. If JULIA_PKGDIR is a relative path, it is interpreted relative to whatever the current
working directory is.
dir(names...) String
Equivalent to normpath(Pkg.dir(),names...) i.e. it appends path components to the package direc-
tory and normalizes the resulting path. In particular, Pkg.dir(pkg) returns the path to the package pkg.
init()
Initialize Pkg.dir() as a package directory. This will be done automatically when the JULIA_PKGDIR is
not set and Pkg.dir() uses its default value.
298 Chapter 2. The Julia Standard Library
Julia Language Documentation, Release 0.4.0-dev
resolve()
Determines an optimal, consistent set of package versions to install or upgrade to. The optimal set of pack-
age versions is based on the contents of Pkg.dir("REQUIRE") and the state of installed packages in
Pkg.dir(), Packages that are no longer required are moved into Pkg.dir(".trash").
edit()
Opens Pkg.dir("REQUIRE") in the editor specied by the VISUAL or EDITOR environment variables;
when the editor command returns, it runs Pkg.resolve() to determine and install a new optimal set of
installed package versions.
add(pkg, vers...)
Add a requirement entry for pkg to Pkg.dir("REQUIRE") and call Pkg.resolve(). If vers are given,
they must be VersionNumber objects and they specify acceptable version intervals for pkg.
rm(pkg)
Remove all requirement entries for pkg from Pkg.dir("REQUIRE") and call Pkg.resolve().
clone(url[, pkg])
Clone a package directly from the git URL url. The package does not need to be a registered in
Pkg.dir("METADATA"). The package repo is cloned by the name pkg if provided; if not provided, pkg is
determined automatically from url.
clone(pkg)
If pkg has a URL registered in Pkg.dir("METADATA"), clone it from that URL on the default branch. The
package does not need to have any registered versions.
available() Vector{ASCIIString}
Returns the names of available packages.
available(pkg) Vector{VersionNumber}
Returns the version numbers available for package pkg.
installed() Dict{ASCIIString,VersionNumber}
Returns a dictionary mapping installed package names to the installed version number of each package.
installed(pkg) Nothing | VersionNumber
If pkg is installed, return the installed version number, otherwise return nothing.
status()
Prints out a summary of what packages are installed and what version and state theyre in.
update()
Update package the metadata repo kept in Pkg.dir("METADATA") then update any xed packages that
can safely be pulled from their origin; then call Pkg.resolve() to determine a new optimal set of packages
versions.
checkout(pkg[, branch=master])
Checkout the Pkg.dir(pkg) repo to the branch branch. Defaults to checking out the master branch. To
go back to using the newest compatible released version, use Pkg.free(pkg)
pin(pkg)
Pin pkg at the current version. To go back to using the newest compatible released version, use
Pkg.free(pkg)
pin(pkg, version)
Pin pkg at registered version version.
free(pkg)
Free the package pkg to be managed by the package manager again. It calls Pkg.resolve() to determine
optimal package versions after. This is an inverse for both Pkg.checkout and Pkg.pin.
2.9. Package Manager Functions 299
Julia Language Documentation, Release 0.4.0-dev
build()
Run the build scripts for all installed packages in depth-rst recursive order.
build(pkgs...)
Run the build script in deps/build.jl for each package in pkgs and all of their dependencies in depth-rst
recursive order. This is called automatically by Pkg.resolve() on all installed or updated packages.
generate(pkg, license)
Generate a new package named pkg with one of these license keys: "MIT" or "BSD". If you want to make
a package with a different license, you can edit it afterwards. Generate creates a git repo at Pkg.dir(pkg)
for the package and inside it LICENSE.md, README.md, the julia entrypoint $pkg/src/$pkg.jl, and a
travis test le, .travis.yml.
register(pkg[, url ])
Register pkg at the git URL url, defaulting to the congured origin URL of the git repo Pkg.dir(pkg).
tag(pkg[, ver[, commit ]])
Tag commit as version ver of package pkg and create a version entry in METADATA. If not provided, commit
defaults to the current commit of the pkg repo. If ver is one of the symbols :patch, :minor, :major the
next patch, minor or major version is used. If ver is not provided, it defaults to :patch.
publish()
For each new package version tagged in METADATA not already published, make sure that the tagged package
commits have been pushed to the repo at the registered URL for the package and if they all have, open a pull
request to METADATA.
test()
Run the tests for all installed packages ensuring that each packages test dependencies are installed for the
duration of the test. A package is tested by running its test/runtests.jl le and test dependencies are
specied in test/REQUIRE.
test(pkgs...)
Run the tests for each package in pkgs ensuring that each packages test dependencies are installed for the
duration of the test. A package is tested by running its test/runtests.jl le and test dependencies are
specied in test/REQUIRE.
2.10 Collections and Data Structures
The Collections module contains implementations of some common data structures.
2.10.1 PriorityQueue
The PriorityQueue type is a basic priority queue implementation allowing for arbitrary key and priority types.
Multiple identical keys are not permitted, but the priority of existing keys can be changed efciently.
PriorityQueue(K, V[, ord ])
Construct a new PriorityQueue, with keys of type K and values/priorites of type V. If an order is not given, the
priority queue is min-ordered using the default comparison for V.
enqueue!(pq, k, v)
Insert the a key k into a priority queue pq with priority v.
dequeue!(pq)
Remove and return the lowest priority key from a priority queue.
peek(pq)
Return the lowest priority key from a priority queue without removing that key from the queue.
300 Chapter 2. The Julia Standard Library
Julia Language Documentation, Release 0.4.0-dev
PriorityQueue also behaves similarly to a Dict so that keys can be inserted and priorities accessed or changed
using indexing notation:
# Julia code
pq = Collections.PriorityQueue()
# Insert keys with associated priorities
pq["a"] = 10
pq["b"] = 5
pq["c"] = 15
# Change the priority of an existing key
pq["a"] = 0
2.10.2 Heap Functions
Along with the PriorityQueue type are lower level functions for performing binary heap operations on arrays.
Each function takes an optional ordering argument. If not given, default ordering is used, so that elements popped
from the heap are given in ascending order.
heapify(v[, ord ])
Return a new vector in binary heap order, optionally using the given ordering.
heapify!(v[, ord ])
In-place heapify.
isheap(v[, ord ])
Return true iff an array is heap-ordered according to the given order.
heappush!(v, x[, ord ])
Given a binary heap-ordered array, push a new element x, preserving the heap property. For efciency, this
function does not check that the array is indeed heap-ordered.
heappop!(v[, ord ])
Given a binary heap-ordered array, remove and return the lowest ordered element. For efciency, this function
does not check that the array is indeed heap-ordered.
2.11 Graphics
The Base.Graphics interface is an abstract wrapper; specic packages (e.g., Cairo and Tk/Gtk) implement much
of the functionality.
2.11.1 Geometry
Vec2(x, y)
Creates a point in two dimensions
BoundingBox(xmin, xmax, ymin, ymax)
Creates a box in two dimensions with the given edges
BoundingBox(objs...)
Creates a box in two dimensions that encloses all objects
width(obj)
Computes the width of an object
2.11. Graphics 301
Julia Language Documentation, Release 0.4.0-dev
height(obj)
Computes the height of an object
xmin(obj)
Computes the minimum x-coordinate contained in an object
xmax(obj)
Computes the maximum x-coordinate contained in an object
ymin(obj)
Computes the minimum y-coordinate contained in an object
ymax(obj)
Computes the maximum y-coordinate contained in an object
diagonal(obj)
Return the length of the diagonal of an object
aspect_ratio(obj)
Compute the height/width of an object
center(obj)
Return the point in the center of an object
xrange(obj)
Returns a tuple (xmin(obj), xmax(obj))
yrange(obj)
Returns a tuple (ymin(obj), ymax(obj))
rotate(obj, angle, origin) newobj
Rotates an object around origin by the specied angle (radians), returning a newobject of the same type. Because
of type-constancy, this new object may not always be a strict geometric rotation of the input; for example, if
obj is a BoundingBox the return is the smallest BoundingBox that encloses the rotated input.
shift(obj, dx, dy)
Returns an object shifted horizontally and vertically by the indicated amounts
*
(obj, s::Real)
Scale the width and height of a graphics object, keeping the center xed
+(bb1::BoundingBox, bb2::BoundingBox) BoundingBox
Returns the smallest box containing both boxes
&(bb1::BoundingBox, bb2::BoundingBox) BoundingBox
Returns the intersection, the largest box contained in both boxes
deform(bb::BoundingBox, dxmin, dxmax, dymin, dymax)
Returns a bounding box with all edges shifted by the indicated amounts
isinside(bb::BoundingBox, x, y)
True if the given point is inside the box
isinside(bb::BoundingBox, point)
True if the given point is inside the box
2.12 Unit and Functional Testing
The Test module contains macros and functions related to testing. A default handler is provided to run the tests, and
a custom one can be provided by the user by using the registerhandler() function.
302 Chapter 2. The Julia Standard Library
Julia Language Documentation, Release 0.4.0-dev
2.12.1 Overview
To use the default handler, the macro @test() can be used directly:
julia> using Base.Test
julia> @test 1 == 1
julia> @test 1 == 0
ERROR: test failed: 1 == 0
in error at error.jl:21
in default_handler at test.jl:19
in do_test at test.jl:39
julia> @test error("This is what happens when a test fails")
ERROR: test error during error("This is what happens when a test fails")
This is what happens when a test fails
in error at error.jl:21
in anonymous at test.jl:62
in do_test at test.jl:37
As seen in the examples above, failures or errors will print the abstract syntax tree of the expression in question.
Another macro is provided to check if the given expression throws an exception of type extype,
@test_throws():
julia> @test_throws ErrorException error("An error")
julia> @test_throws BoundsError error("An error")
ERROR: test failed: error("An error")
in error at error.jl:21
in default_handler at test.jl:19
in do_test_throws at test.jl:55
julia> @test_throws DomainError throw(DomainError())
julia> @test_throws DomainError throw(EOFError())
ERROR: test failed: throw(EOFError())
in error at error.jl:21
in default_handler at test.jl:19
in do_test_throws at test.jl:55
As oating point comparisons can be imprecise, two additional macros exist taking in account small numerical errors:
julia> @test_approx_eq 1. 0.999999999
ERROR: assertion failed: |1.0 - 0.999999999| < 2.220446049250313e-12
1.0 = 1.0
0.999999999 = 0.999999999
in test_approx_eq at test.jl:75
in test_approx_eq at test.jl:80
julia> @test_approx_eq 1. 0.9999999999999
julia> @test_approx_eq_eps 1. 0.999 1e-2
julia> @test_approx_eq_eps 1. 0.999 1e-3
ERROR: assertion failed: |1.0 - 0.999| <= 0.001
1.0 = 1.0
0.999 = 0.999
difference = 0.0010000000000000009 > 0.001
2.12. Unit and Functional Testing 303
Julia Language Documentation, Release 0.4.0-dev
in error at error.jl:22
in test_approx_eq at test.jl:68
2.12.2 Handlers
A handler is a function dened for three kinds of arguments: Success, Failure, Error:
# An example definition of a test handler
test_handler(r::Success) = nothing
test_handler(r::Failure) = error("test failed: $(r.expr)")
test_handler(r::Error) = rethrow(r)
A different handler can be used for a block (with with_handler()):
julia> using Base.Test
julia> custom_handler(r::Test.Success) = println("Success on $(r.expr)")
custom_handler (generic function with 1 method)
julia> custom_handler(r::Test.Failure) = error("Error on custom handler: $(r.expr)")
custom_handler (generic function with 2 methods)
julia> custom_handler(r::Test.Error) = rethrow(r)
custom_handler (generic function with 3 methods)
julia> Test.with_handler(custom_handler) do
@test 1 == 1
@test 1 != 1
end
Success on :((1==1))
ERROR: Error on custom handler: :((1!=1))
in error at error.jl:21
in custom_handler at none:1
in do_test at test.jl:39
in anonymous at no file:3
in task_local_storage at task.jl:28
in with_handler at test.jl:24
The Success and Failure types include an additonal eld, resultexpr, which is a partially evaluated expres-
sion. For example, in a comparison it will contain an expression with the left and right sides evaluated.
2.12.3 Macros
@test(ex)
Test the expression ex and calls the current handler to handle the result.
@test_throws(extype, ex)
Test that the expression ex throws an exception of type extype and calls the current handler to handle the
result.
@test_approx_eq(a, b)
Test two oating point numbers a and b for equality taking in account small numerical errors.
@test_approx_eq_eps(a, b, tol)
Test two oating point numbers a and b for equality taking in account a margin of tolerance given by tol.
304 Chapter 2. The Julia Standard Library
Julia Language Documentation, Release 0.4.0-dev
2.12.4 Functions
with_handler(f, handler)
Run the function f using the handler as the handler.
2.13 Testing Base Julia
Julia is under rapid development and has an extensive test suite to verify functionality across multiple platforms. If
you build Julia from source, you can run this test suite with make test. In a binary install, you can run the test suite
using Base.runtests().
runtests([tests=[all][, numcores=iceil(CPU_CORES/2) ]])
Run the Julia unit tests listed in tests, which can be either a string or an array of strings, using numcores
processors.
2.14 Proling
The Profile module provides tools to help developers improve the performance of their code. When used, it takes
measurements on running code, and produces output that helps you understand how much time is spent on individual
line(s). The most common usage is to identify bottlenecks as targets for optimization.
Profile implements what is known as a sampling or statistical proler. It works by periodically taking a backtrace
during the execution of any task. Each backtrace captures the currently-running function and line number, plus the
complete chain of function calls that led to this line, and hence is a snapshot of the current state of execution.
If much of your run time is spent executing a particular line of code, this line will show up frequently in the set of all
backtraces. In other words, the cost of a given lineor really, the cost of the sequence of function calls up to and
including this lineis proportional to how often it appears in the set of all backtraces.
A sampling proler does not provide complete line-by-line coverage, because the backtraces occur at intervals (by
default, 1 ms). However, this design has important strengths:
You do not have to make any modications to your code to take timing measurements (in contrast to the alter-
native instrumenting proler).
It can prole into Julias core code and even (optionally) into C and Fortran libraries.
By running infrequently there is very little performance overhead; while proling, your code will run at nearly
native speed.
For these reasons, its recommended that you try using the built-in sampling proler before considering any alterna-
tives.
2.14.1 Basic usage
Lets work with a simple test case:
function myfunc()
A = rand(100, 100, 200)
maximum(A)
end
Its a good idea to rst run the code you intend to prole at least once (unless you want to prole Julias JIT-compiler):
2.13. Testing Base Julia 305
Julia Language Documentation, Release 0.4.0-dev
julia> myfunc() # run once to force compilation
Now were ready to prole this function:
julia> @profile myfunc()
To see the proling results, there is a graphical browser available, but here well use the text-based display that comes
with the standard library:
julia> Profile.print()
23 client.jl; _start; line: 373
23 client.jl; run_repl; line: 166
23 client.jl; eval_user_input; line: 91
23 profile.jl; anonymous; line: 14
8 none; myfunc; line: 2
8 dSFMT.jl; dsfmt_gv_fill_array_close_open!; line: 128
15 none; myfunc; line: 3
2 reduce.jl; max; line: 35
2 reduce.jl; max; line: 36
11 reduce.jl; max; line: 37
Each line of this display represents a particular spot (line number) in the code. Indentation is used to indicate the
nested sequence of function calls, with more-indented lines being deeper in the sequence of calls. In each line, the rst
eld indicates the number of backtraces (samples) taken at this line or in any functions executed by this line. The
second eld is the le name, followed by a semicolon; the third is the function name followed by a semicolon, and
the fourth is the line number. Note that the specic line numbers may change as Julias code changes; if you want to
follow along, its best to run this example yourself.
In this example, we can see that the top level is client.jls _start function. This is the rst Julia function that
gets called when you launch julia. If you examine line 373 of client.jl, youll see that (at the time of this writing)
it calls run_repl, mentioned on the second line. This in turn calls eval_user_input. These are the functions
in client.jl that interpret what you type at the REPL, and since were working interactively these functions were
invoked when we entered @profile myfunc(). The next line reects actions taken in the @profile macro.
The rst line shows that 23 backtraces were taken at line 373 of client.jl, but its not that this line was expensive
on its own: the second line reveals that all 23 of these backtraces were actually triggered inside its call to run_repl,
and so on. To nd out which operations are actually taking the time, we need to look deeper in the call chain.
The rst important line in this output is this one:
8 none; myfunc; line: 2
none refers to the fact that we dened myfunc in the REPL, rather than putting it in a le; if we had used a le, this
would show the le name. Line 2 of myfunc() contains the call to rand, and there were 8 (out of 23) backtraces
that occurred at this line. Below that, you can see a call to dsfmt_gv_fill_array_close_open! inside
dSFMT.jl. You might be surprised not to see the rand function listed explicitly: thats because rand is inlined,
and hence doesnt appear in the backtraces.
A little further down, you see:
15 none; myfunc; line: 3
Line 3 of myfunc contains the call to max, and there were 15 (out of 23) backtraces taken here. Below that, you can
see the specic places in base/reduce.jl that carry out the time-consuming operations in the max function for
this type of input data.
Overall, we can tentatively conclude that nding the maximum element is approximately twice as expensive as gener-
ating the random numbers. We could increase our condence in this result by collecting more samples:
306 Chapter 2. The Julia Standard Library
Julia Language Documentation, Release 0.4.0-dev
julia> @profile (for i = 1:100; myfunc(); end)
julia> Profile.print()
3121 client.jl; _start; line: 373
3121 client.jl; run_repl; line: 166
3121 client.jl; eval_user_input; line: 91
3121 profile.jl; anonymous; line: 1
848 none; myfunc; line: 2
842 dSFMT.jl; dsfmt_gv_fill_array_close_open!; line: 128
1510 none; myfunc; line: 3
74 reduce.jl; max; line: 35
122 reduce.jl; max; line: 36
1314 reduce.jl; max; line: 37
In general, if you have N samples collected at a line, you can expect an uncertainty on the order of sqrt(N) (barring
other sources of noise, like how busy the computer is with other tasks). The major exception to this rule is garbage-
collection, which runs infrequently but tends to be quite expensive. (Since julias garbage collector is written in C,
such events can be detected using the C=true output mode described below, or by using ProleView.)
This illustrates the default tree dump; an alternative is the at dump, which accumulates counts independent of
their nesting:
julia> Profile.print(format=:flat)
Count File Function Line
3121 client.jl _start 373
3121 client.jl eval_user_input 91
3121 client.jl run_repl 166
842 dSFMT.jl dsfmt_gv_fill_array_close_open! 128
848 none myfunc 2
1510 none myfunc 3
3121 profile.jl anonymous 1
74 reduce.jl max 35
122 reduce.jl max 36
1314 reduce.jl max 37
If your code has recursion, one potentially-confusing point is that a line in a child function can accumulate more
counts than there are total backtraces. Consider the following function denitions:
dumbsum(n::Integer) = n == 1 ? 1 : 1 + dumbsum(n-1)
dumbsum3() = dumbsum(3)
If you were to prole dumbsum3, and a backtrace was taken while it was executing dumbsum(1), the backtrace
would look like this:
dumbsum3
dumbsum(3)
dumbsum(2)
dumbsum(1)
Consequently, this child function gets 3 counts, even though the parent only gets one. The tree representation makes
this much clearer, and for this reason (among others) is probably the most useful way to view the results.
2.14.2 Accumulation and clearing
Results from @profile accumulate in a buffer; if you run multiple pieces of code under @profile, then
Profile.print() will show you the combined results. This can be very useful, but sometimes you want to
start fresh; you can do so with Profile.clear().
2.14. Proling 307
Julia Language Documentation, Release 0.4.0-dev
2.14.3 Options for controlling the display of prole results
Profile.print() has more options than weve described so far. Lets see the full declaration:
function print(io::IO = STDOUT, data = fetch(); format = :tree, C = false, combine = true, cols = tty_cols())
Lets discuss these arguments in order:
The rst argument allows you to save the results to a le, but the default is to print to STDOUT (the console).
The second argument contains the data you want to analyze; by default that is obtained from
Profile.fetch(), which pulls out the backtraces from a pre-allocated buffer. For example, if you want
to prole the proler, you could say:
data = copy(Profile.fetch())
Profile.clear()
@profile Profile.print(STDOUT, data) # Prints the previous results
Profile.print() # Prints results from Profile.print()
The rst keyword argument, format, was introduced above. The possible choices are :tree and :flat.
C, if set to true, allows you to see even the calls to C code. Try running the introductory example with
Profile.print(C = true). This can be extremely helpful in deciding whether its Julia code or C code
that is causing a bottleneck; setting C=true also improves the interpretability of the nesting, at the cost of
longer prole dumps.
Some lines of code contain multiple operations; for example, s += A[i] contains both an array reference
(A[i]) and a sum operation. These correspond to different lines in the generated machine code, and hence
there may be two or more different addresses captured during backtraces on this line. combine=true lumps
them together, and is probably what you typically want, but you can generate an output separately for each
unique instruction pointer with combine=false.
cols allows you to control the number of columns that you are willing to use for display. When the text would
be wider than the display, you might see output like this:
33 inference.jl; abstract_call; line: 645
33 inference.jl; abstract_call; line: 645
33 ...rence.jl; abstract_call_gf; line: 567
33 ...nce.jl; typeinf; line: 1201
+1 5 ...nce.jl; ...t_interpret; line: 900
+3 5 ...ence.jl; abstract_eval; line: 758
+4 5 ...ence.jl; ...ct_eval_call; line: 733
+6 5 ...ence.jl; abstract_call; line: 645
File/function names are sometimes truncated (with ...), and indentation is truncated with a +n at the beginning,
where n is the number of extra spaces that would have been inserted, had there been room. If you want a
complete prole of deeply-nested code, often a good idea is to save to a le and use a very wide cols setting:
s = open("/tmp/prof.txt","w")
Profile.print(s,cols = 500)
close(s)
2.14.4 Conguration
@profile just accumulates backtraces, and the analysis happens when you call Profile.print(). For a long-
running computation, its entirely possible that the pre-allocated buffer for storing backtraces will be lled. If that
happens, the backtraces stop but your computation continues. As a consequence, you may miss some important
proling data (you will get a warning when that happens).
308 Chapter 2. The Julia Standard Library
Julia Language Documentation, Release 0.4.0-dev
You can obtain and congure the relevant parameters this way:
Profile.init() # returns the current settings
Profile.init(n, delay)
Profile.init(delay = 0.01)
n is the total number of instruction pointers you can store, with a default value of 10^6. If your typical backtrace
is 20 instruction pointers, then you can collect 50000 backtraces, which suggests a statistical uncertainty of less than
1%. This may be good enough for most applications.
Consequently, you are more likely to need to modify delay, expressed in seconds, which sets the amount of time that
Julia gets between snapshots to perform the requested computations. A very long-running job might not need frequent
backtraces. The default setting is delay = 0.001. Of course, you can decrease the delay as well as increase it;
however, the overhead of proling grows once the delay becomes similar to the amount of time needed to take a
backtrace (~30 microseconds on the authors laptop).
2.14.5 Function reference
@profile()
@profile <expression> runs your expression while taking periodic backtraces. These are appended to
an internal buffer of backtraces.
clear()
Clear any existing backtraces from the internal buffer.
print([io::IO = STDOUT ], [data::Vector]; format = :tree, C = false, combine = true, cols = tty_cols())
Prints proling results to io (by default, STDOUT). If you do not supply a data vector, the internal buffer of
accumulated backtraces will be used. format can be :tree or :flat. If C==true, backtraces from C
and Fortran code are shown. combine==true merges instruction pointers that correspond to the same line of
code. cols controls the width of the display.
print([io::IO = STDOUT ], data::Vector, lidict::Dict; format = :tree, combine = true, cols = tty_cols())
Prints proling results to io. This variant is used to examine results exported by a previous call to
Profile.retrieve(). Supply the vector data of backtraces and a dictionary lidict of line infor-
mation.
init(; n::Integer, delay::Float64)
Congure the delay between backtraces (measured in seconds), and the number n of instruction pointers that
may be stored. Each instruction pointer corresponds to a single line of code; backtraces generally consist of a
long list of instruction pointers. Default settings can be obtained by calling this function with no arguments, and
each can be set independently using keywords or in the order (n, delay).
fetch() data
Returns a reference to the internal buffer of backtraces. Note that subsequent operations, like
Profile.clear(), can affect data unless you rst make a copy. Note that the values in data have
meaning only on this machine in the current session, because it depends on the exact memory addresses used in
JIT-compiling. This function is primarily for internal use; Profile.retrieve() may be a better choice for
most users.
retrieve() data, lidict
Exports proling results in a portable format, returning the set of all backtraces (data) and a dictionary that
maps the (session-specic) instruction pointers in data to LineInfo values that store the le name, function
name, and line number. This function allows you to save proling results for future analysis.
2.14. Proling 309
Julia Language Documentation, Release 0.4.0-dev
310 Chapter 2. The Julia Standard Library
Bibliography
[Clarke61] Arthur C. Clarke, Proles of the Future (1961): Clarkes Third Law.
[Bischof1987] C Bischof and C Van Loan, The WY representation for products of Householder matrices, SIAM J Sci
Stat Comput 8 (1987), s2-s13. doi:10.1137/0908009
[Schreiber1989] R Schreiber and C Van Loan, A storage-efcient WY representation for products of Householder
transformations, SIAM J Sci Stat Comput 10 (1989), 53-57. doi:10.1137/0910005
[Bunch1977] J R Bunch and L Kaufman, Some stable methods for calculating inertia and solving symmetric linear
systems, Mathematics of Computation 31:137 (1977), 163-179. url.
311