The Standard Library¶
Introduction¶
The Julia standard library contains a range of functions and macros appropriate for performing scientific and numerical computing, but is also as broad as those of many general purpose programming languages. Additional functionality is available from a growing collection of available packages. Functions are grouped by topic below.
Some general notes:
- Except for functions in built-in modules (
Pkg
,Collections
,Graphics
,Test
andProfile
), all functions documented here are directly available for use in programs. - To use module functions, use
import Module
to import the module, andModule.fn(x)
to use the functions. - Alternatively,
using Module
will import all exportedModule
functions into the current namespace. - By convention, function names ending with an exclamation point (
!
) modify their arguments. Some functions have both modifying (e.g.,sort!
) and non-modifying (sort
) versions.
Getting Around¶
-
exit
([code])¶ Quit (or control-D at the prompt). The default exit code is zero, indicating that the processes completed successfully.
-
quit
()¶ Quit the program indicating that the processes completed succesfully. This function calls
exit(0)
(seeexit()
).
-
atexit
(f)¶ Register a zero-argument function to be called at exit.
-
isinteractive
() → Bool¶ Determine whether Julia is running an interactive session.
-
whos
([Module,] [pattern::Regex])¶ Print information about global variables in a module, optionally restricted to those matching
pattern
.
-
edit
(file::String[, line])¶ Edit a file optionally providing a line number to edit at. Returns to the julia prompt when you quit the editor.
-
edit
(function[, types]) Edit the definition of a function, optionally specifying a tuple of types to indicate which method to edit.
-
@edit
()¶ Evaluates the arguments to the function call, determines their types, and calls the
edit
function on the resulting expression
-
less
(file::String[, line])¶ Show a file using the default pager, optionally providing a starting line number. Returns to the julia prompt when you quit the pager.
-
less
(function[, types]) Show the definition of a function using the default pager, optionally specifying a tuple of types to indicate which method to see.
-
@less
()¶ Evaluates the arguments to the function call, determines their types, and calls the
less
function on the resulting expression
-
clipboard
(x)¶ Send a printed form of
x
to the operating system clipboard (“copy”).
-
clipboard
() → String Return a string with the contents of the operating system clipboard (“paste”).
-
require
(file::String...)¶ Load source files once, in the context of the
Main
module, on every active node, searching standard locations for files.require
is considered a top-level operation, so it sets the currentinclude
path but does not use it to search for files (see help forinclude
). This function is typically used to load library code, and is implicitly called byusing
to load packages.When searching for files,
require
first looks in the current working directory, then looks for package code underPkg.dir()
, then tries paths in the global arrayLOAD_PATH
.
-
reload
(file::String)¶ Like
require
, except forces loading of files regardless of whether they have been loaded before. Typically used when interactively developing libraries.
-
include
(path::String)¶ Evaluate the contents of a source file in the current context. During including, a task-local include path is set to the directory containing the file. Nested calls to
include
will search relative to that path. All paths refer to files on node 1 when running in parallel, and files will be fetched from node 1. This function is typically used to load source interactively, or to combine files in packages that are broken into multiple source files.
-
include_string
(code::String)¶ Like
include
, except reads code from the given string rather than from a file. Since there is no file path involved, no path processing or fetching from node 1 is done.
-
help
(name)¶ Get help for a function.
name
can be an object or a string.
-
apropos
(string)¶ Search documentation for functions related to
string
.
-
which
(f, types)¶ Return the method of
f
(aMethod
object) that will be called for arguments with the given types.
-
@which
()¶ Evaluates the arguments to the function call, determines their types, and calls the
which
function on the resulting expression
-
methods
(f[, types])¶ Show all methods of
f
with their argument types.If
types
is specified, an array of methods whose types match is returned.
-
methodswith
(typ[, showparents])¶ Return an array of methods with an argument of type
typ
. If optionalshowparents
istrue
, also return arguments with a parent type oftyp
, excluding typeAny
.
-
@show
()¶ Show an expression and result, returning the result
-
versioninfo
([verbose::Bool])¶ Print information about the version of Julia in use. If the
verbose
argument is true, detailed system information is shown as well.
-
workspace
()¶ Replace the top-level module (
Main
) with a new one, providing a clean workspace. The previousMain
module is made available asLastMain
. A previously-loaded package can be accessed using a statement such asusing LastMain.Package
.This function should only be used interactively.
All Objects¶
-
is
(x, y) → Bool¶ Determine whether
x
andy
are identical, in the sense that no program could distinguish them. Compares mutable objects by address in memory, and compares immutable objects (such as numbers) by contents at the bit level. This function is sometimes calledegal
. The===
operator is an alias for this function.
-
isa
(x, type) → Bool¶ Determine whether
x
is of the giventype
.
-
isequal
(x, y)¶ Similar to
==
, except treats all floating-pointNaN
values as equal to each other, and treats-0.0
as unequal to0.0
. For values that are not floating-point,isequal
is the same as==
.isequal
is the comparison function used by hash tables (Dict
).isequal(x,y)
must imply thathash(x) == hash(y)
.Collections typically implement
isequal
by callingisequal
recursively on all contents.Scalar types generally do not need to implement
isequal
, unless they represent floating-point numbers amenable to a more efficient implementation than that provided as a generic fallback (based onisnan
,signbit
, and==
).
-
isless
(x, y)¶ Test whether
x
is less thany
, according to a canonical total order. Values that are normally unordered, such asNaN
, are ordered in an arbitrary but consistent fashion. This is the default comparison used bysort
. Non-numeric types with a canonical total order should implement this function. Numeric types only need to implement it if they have special values such asNaN
.
-
ifelse
(condition::Bool, x, y)¶ Return
x
ifcondition
is true, otherwise returny
. This differs from?
orif
in that it is an ordinary function, so all the arguments are evaluated first.
-
lexcmp
(x, y)¶ Compare
x
andy
lexicographically and return -1, 0, or 1 depending on whetherx
is less than, equal to, or greater thany
, respectively. This function should be defined for lexicographically comparable types, andlexless
will calllexcmp
by default.
-
lexless
(x, y)¶ Determine whether
x
is lexicographically less thany
.
-
typeof
(x)¶ Get the concrete type of
x
.
-
tuple
(xs...)¶ Construct a tuple of the given objects.
-
ntuple
(n, f::Function)¶ Create a tuple of length
n
, computing each element asf(i)
, wherei
is the index of the element.
-
object_id
(x)¶ Get a unique integer id for
x
.object_id(x)==object_id(y)
if and only ifis(x,y)
.
-
hash
(x[, h])¶ Compute an integer hash code such that
isequal(x,y)
implieshash(x)==hash(y)
. The optional second argumenth
is a hash code to be mixed with the result. New types should implement the 2-argument form.
-
finalizer
(x, function)¶ Register a function
f(x)
to be called when there are no program-accessible references tox
. The behavior of this function is unpredictable ifx
is of a bits type.
-
copy
(x)¶ Create a shallow copy of
x
: the outer structure is copied, but not all internal values. For example, copying an array produces a new array with identically-same elements as the original.
-
deepcopy
(x)¶ Create a deep copy of
x
: everything is copied recursively, resulting in a fully independent object. For example, deep-copying an array produces a new array whose elements are deep-copies of the original elements.As a special case, functions can only be actually deep-copied if they are anonymous, otherwise they are just copied. The difference is only relevant in the case of closures, i.e. functions which may contain hidden internal references.
While it isn’t normally necessary, user-defined types can override the default
deepcopy
behavior by defining a specialized version of the functiondeepcopy_internal(x::T, dict::ObjectIdDict)
(which shouldn’t otherwise be used), whereT
is the type to be specialized for, anddict
keeps track of objects copied so far within the recursion. Within the definition,deepcopy_internal
should be used in place ofdeepcopy
, and thedict
variable should be updated as appropriate before returning.
-
isdefined
([object, ]index | symbol)¶ Tests whether an assignable location is defined. The arguments can be an array and index, a composite object and field name (as a symbol), or a module and a symbol. With a single symbol argument, tests whether a global variable with that name is defined in
current_module()
.
-
convert
(type, x)¶ Try to convert
x
to the given type. Conversions from floating point to integer, rational to integer, and complex to real will raise anInexactError
ifx
cannot be represented exactly in the new type.
-
promote
(xs...)¶ Convert all arguments to their common promotion type (if any), and return them all (as a tuple).
-
oftype
(x, y)¶ Convert
y
to the type ofx
.
-
widen
(type | x)¶ If the argument is a type, return a “larger” type (for numeric types, this will be a type with at least as much range and precision as the argument, and usually more). Otherwise the argument
x
is converted towiden(typeof(x))
.julia> widen(Int32) Int64
julia> widen(1.5f0) 1.5
-
identity
(x)¶ The identity function. Returns its argument.
Types¶
-
super
(T::DataType)¶ Return the supertype of DataType T
-
issubtype
(type1, type2)¶ True if and only if all values of
type1
are also oftype2
. Can also be written using the<:
infix operator astype1 <: type2
.
-
<:
(T1, T2)¶ Subtype operator, equivalent to
issubtype(T1,T2)
.
-
subtypes
(T::DataType)¶ Return a list of immediate subtypes of DataType T. Note that all currently loaded subtypes are included, including those not visible in the current module.
-
subtypetree
(T::DataType)¶ Return a nested list of all subtypes of DataType T. Note that all currently loaded subtypes are included, including those not visible in the current module.
-
typemin
(type)¶ The lowest value representable by the given (real) numeric type.
-
typemax
(type)¶ The highest value representable by the given (real) numeric type.
-
realmin
(type)¶ The smallest in absolute value non-subnormal value representable by the given floating-point type
-
realmax
(type)¶ The highest finite value representable by the given floating-point type
-
maxintfloat
(type)¶ The largest integer losslessly representable by the given floating-point type
-
sizeof
(type)¶ Size, in bytes, of the canonical binary representation of the given type, if any.
-
eps
([type])¶ The distance between 1.0 and the next larger representable floating-point value of
type
. Only floating-point types are sensible arguments. Iftype
is omitted, theneps(Float64)
is returned.
-
eps
(x) The distance between
x
and the next larger representable floating-point value of the same type asx
.
-
promote_type
(type1, type2)¶ Determine a type big enough to hold values of each argument type without loss, whenever possible. In some cases, where no type exists which to which both types can be promoted losslessly, some loss is tolerated; for example,
promote_type(Int64,Float64)
returnsFloat64
even though strictly, not allInt64
values can be represented exactly asFloat64
values.
-
promote_rule
(type1, type2)¶ Specifies what type should be used by
promote
when given values of typestype1
andtype2
. This function should not be called directly, but should have definitions added to it for new types as appropriate.
-
getfield
(value, name::Symbol)¶ Extract a named field from a value of composite type. The syntax
a.b
callsgetfield(a, :b)
, and the syntaxa.(b)
callsgetfield(a, b)
.
-
setfield!
(value, name::Symbol, x)¶ Assign
x
to a named field invalue
of composite type. The syntaxa.b = c
callssetfield!(a, :b, c)
, and the syntaxa.(b) = c
callssetfield!(a, b, c)
.
-
fieldoffsets
(type)¶ The byte offset of each field of a type relative to the data start. For example, we could use it in the following manner to summarize information about a struct type:
julia> structinfo(T) = [zip(fieldoffsets(T),names(T),T.types)...]; julia> structinfo(StatStruct) 12-element Array{(Int64,Symbol,DataType),1}: (0,:device,Uint64) (8,:inode,Uint64) (16,:mode,Uint64) (24,:nlink,Int64) (32,:uid,Uint64) (40,:gid,Uint64) (48,:rdev,Uint64) (56,:size,Int64) (64,:blksize,Int64) (72,:blocks,Int64) (80,:mtime,Float64) (88,:ctime,Float64)
-
fieldtype
(value, name::Symbol)¶ Determine the declared type of a named field in a value of composite type.
-
isbits
(T)¶ True if
T
is a “plain data” type, meaning it is immutable and contains no references to other values. Typical examples are numeric types such asUint8
,Float64
, andComplex{Float64}
.julia> isbits(Complex{Float64}) true julia> isbits(Complex) false
-
isleaftype
(T)¶ Determine whether
T
is a concrete type that can have instances, meaning its only subtypes are itself andNone
(butT
itself is notNone
).
-
typejoin
(T, S)¶ Compute a type that contains both
T
andS
.
-
typeintersect
(T, S)¶ Compute a type that contains the intersection of
T
andS
. Usually this will be the smallest such type or one close to it.
Generic Functions¶
-
apply
(f, x...)¶ Accepts a function and several arguments, each of which must be iterable. The elements generated by all the arguments are appended into a single list, which is then passed to
f
as its argument list.julia> function f(x, y) # Define a function f x + y end; julia> apply(f, [1 2]) # Apply f with 1 and 2 as arguments 3
apply
is called to implement the...
argument splicing syntax, and is usually not called directly:apply(f,x) === f(x...)
-
method_exists
(f, tuple) → Bool¶ Determine whether the given generic function has a method matching the given tuple of argument types.
julia> method_exists(length, (Array,)) true
-
applicable
(f, args...) → Bool¶ Determine whether the given generic function has a method applicable to the given arguments.
julia> function f(x, y) x + y end; julia> applicable(f, 1) false julia> applicable(f, 1, 2) true
-
invoke
(f, (types...), args...)¶ Invoke a method for the given generic function matching the specified types (as a tuple), on the specified arguments. The arguments must be compatible with the specified types. This allows invoking a method other than the most specific matching method, which is useful when the behavior of a more general definition is explicitly needed (often as part of the implementation of a more specific method of the same function).
-
|>
(x, f)¶ Applies a function to the preceding argument. This allows for easy function chaining.
julia> [1:5] |> x->x.^2 |> sum |> inv 0.01818181818181818
Syntax¶
-
eval
([m::Module, ]expr::Expr)¶ Evaluate an expression in the given module and return the result. Every module (except those defined with
baremodule
) has its own 1-argument definition ofeval
, which evaluates expressions in that module.
-
@eval
()¶ Evaluate an expression and return the value.
-
evalfile
(path::String)¶ Evaluate all expressions in the given file, and return the value of the last one. No other processing (path searching, fetching from node 1, etc.) is performed.
-
esc
(e::ANY)¶ Only valid in the context of an Expr returned from a macro. Prevents the macro hygiene pass from turning embedded variables into gensym variables. See the man-macros section of the Metaprogramming chapter of the manual for more details and examples.
-
gensym
([tag])¶ Generates a symbol which will not conflict with other variable names.
-
@gensym
()¶ Generates a gensym symbol for a variable. For example,
@gensym x y
is transformed intox = gensym("x"); y = gensym("y")
.
-
parse
(str, start; greedy=true, raise=true)¶ Parse the expression string and return an expression (which could later be passed to eval for execution). Start is the index of the first character to start parsing. If
greedy
is true (default),parse
will try to consume as much input as it can; otherwise, it will stop as soon as it has parsed a valid expression. Ifraise
is true (default), syntax errors will raise an error; otherwise,parse
will return an expression that will raise an error upon evaluation.
-
parse
(str; raise=true) Parse the whole string greedily, returning a single expression. An error is thrown if there are additional characters after the first expression. If
raise
is true (default), syntax errors will raise an error; otherwise,parse
will return an expression that will raise an error upon evaluation.
Iteration¶
Sequential iteration is implemented by the methods start
, done
, and
next
. The general for
loop:
for i = I
# body
end
is translated to:
state = start(I)
while !done(I, state)
(i, state) = next(I, state)
# body
end
The state
object may be anything, and should be chosen appropriately for each iterable type.
-
start
(iter) → state¶ Get initial iteration state for an iterable object
-
done
(iter, state) → Bool¶ Test whether we are done iterating
-
next
(iter, state) → item, state¶ For a given iterable object and iteration state, return the current item and the next iteration state
-
zip
(iters...)¶ For a set of iterable objects, returns an iterable of tuples, where the
i
th tuple contains thei
th component of each input iterable.Note that
zip
is its own inverse:[zip(zip(a...)...)...] == [a...]
.
-
enumerate
(iter)¶ Return an iterator that yields
(i, x)
wherei
is an index starting at 1, andx
is thei
th value from the given iterator. It’s useful when you need not only the valuesx
over which you are iterating, but also the indexi
of the iterations.julia> a = ["a", "b", "c"]; julia> for (index, value) in enumerate(a) println("$index $value") end 1 a 2 b 3 c
Fully implemented by: Range
, Range1
, NDRange
, Tuple
, Real
, AbstractArray
, IntSet
, ObjectIdDict
, Dict
, WeakKeyDict
, EachLine
, String
, Set
, Task
.
General Collections¶
-
isempty
(collection) → Bool¶ Determine whether a collection is empty (has no elements).
julia> isempty([]) true julia> isempty([1 2 3]) false
-
empty!
(collection) → collection¶ Remove all elements from a
collection
.
-
length
(collection) → Integer¶ For ordered, indexable collections, the maximum index
i
for whichgetindex(collection, i)
is valid. For unordered collections, the number of elements.
-
endof
(collection) → Integer¶ Returns the last index of the collection.
julia> endof([1,2,4]) 3
Fully implemented by: Range
, Range1
, Tuple
, Number
, AbstractArray
, IntSet
, Dict
, WeakKeyDict
, String
, Set
.
Iterable Collections¶
-
in
(item, collection) → Bool¶ Determine whether an item is in the given collection, in the sense that it is
==
to one of the values generated by iterating over the collection. Some collections need a slightly different definition; for example Sets check whether the item isisequal
to one of the elements. Dicts look for(key,value)
pairs, and the key is compared usingisequal
. To test for the presence of a key in a dictionary, usehaskey
ork in keys(dict)
.
-
eltype
(collection)¶ Determine the type of the elements generated by iterating
collection
. For associative collections, this will be a(key,value)
tuple type.
-
indexin
(a, b)¶ Returns a vector containing the highest index in
b
for each value ina
that is a member ofb
. The output vector contains 0 wherevera
is not a member ofb
.
-
findin
(a, b)¶ Returns the indices of elements in collection
a
that appear in collectionb
-
unique
(itr[, dim])¶ Returns an array containing only the unique elements of the iterable
itr
, in the order that the first of each set of equivalent elements originally appears. Ifdim
is specified, returns unique regions of the arrayitr
alongdim
.
-
reduce
(op, v0, itr)¶ Reduce the given collection
ìtr
with the given binary operator. Reductions for certain commonly-used operators have special implementations which should be used instead:maximum(itr)
,minimum(itr)
,sum(itr)
,prod(itr)
,any(itr)
,all(itr)
.The associativity of the reduction is implementation-dependent. This means that you can’t use non-associative operations like
-
because it is undefined whetherreduce(-,[1,2,3])
should be evaluated as(1-2)-3
or1-(2-3)
. Usefoldl
orfoldr
instead for guaranteed left or right associativity.Some operations accumulate error, and parallelism will also be easier if the reduction can be executed in groups. Future versions of Julia might change the algorithm. Note that the elements are not reordered if you use an ordered collection.
-
reduce
(op, itr) Like
reduce
but using the first element as v0.
-
foldl
(op, v0, itr)¶ Like
reduce
, but with guaranteed left associativity.
-
foldl
(op, itr) Like
foldl
, but using the first element as v0.
-
foldr
(op, v0, itr)¶ Like
reduce
, but with guaranteed right associativity.
-
foldr
(op, itr) Like
foldr
, but using the last element as v0.
-
maximum
(itr)¶ Returns the largest element in a collection.
-
maximum
(A, dims) Compute the maximum value of an array over the given dimensions.
-
maximum!
(r, A)¶ Compute the maximum value of
A
over the singleton dimensions ofr
, and write results tor
.
-
minimum
(itr)¶ Returns the smallest element in a collection.
-
minimum
(A, dims) Compute the minimum value of an array over the given dimensions.
-
minimum!
(r, A)¶ Compute the minimum value of
A
over the singleton dimensions ofr
, and write results tor
.
-
extrema
(itr)¶ Compute both the minimum and maximum element in a single pass, and return them as a 2-tuple.
-
indmax
(itr) → Integer¶ Returns the index of the maximum element in a collection.
-
indmin
(itr) → Integer¶ Returns the index of the minimum element in a collection.
-
findmax
(itr) -> (x, index)¶ Returns the maximum element and its index.
-
findmax
(A, dims) -> (maxval, index) For an array input, returns the value and index of the maximum over the given dimensions.
-
findmin
(itr) -> (x, index)¶ Returns the minimum element and its index.
-
findmin
(A, dims) -> (minval, index) For an array input, returns the value and index of the minimum over the given dimensions.
-
maxabs
(itr)¶ Compute the maximum absolute value of a collection of values.
-
maxabs
(A, dims) Compute the maximum absolute values over given dimensions.
-
maxabs!
(r, A)¶ Compute the maximum absolute values over the singleton dimensions of
r
, and write values tor
.
-
minabs
(itr)¶ Compute the minimum absolute value of a collection of values.
-
minabs
(A, dims) Compute the minimum absolute values over given dimensions.
-
minabs!
(r, A)¶ Compute the minimum absolute values over the singleton dimensions of
r
, and write values tor
.
-
sum
(itr)¶ Returns the sum of all elements in a collection.
-
sum
(A, dims) Sum elements of an array over the given dimensions.
-
sum!
(r, A)¶ Sum elements of
A
over the singleton dimensions ofr
, and write results tor
.
-
sum
(f, itr) Sum the results of calling function
f
on each element ofitr
.
-
sumabs
(itr)¶ Sum absolute values of all elements in a collection. This is equivalent to sum(abs(itr)) but faster.
-
sumabs
(A, dims) Sum absolute values of elements of an array over the given dimensions.
-
sumabs!
(r, A)¶ Sum absolute values of elements of
A
over the singleton dimensions ofr
, and write results tor
.
-
sumabs2
(itr)¶ Sum squared absolute values of all elements in a collection. This is equivalent to sum(abs2(itr)) but faster.
-
sumabs2
(A, dims) Sum squared absolute values of elements of an array over the given dimensions.
-
sumabs2!
(r, A)¶ Sum squared absolute values of elements of
A
over the singleton dimensions ofr
, and write results tor
.
-
prod
(itr)¶ Returns the product of all elements of a collection.
-
prod
(A, dims) Multiply elements of an array over the given dimensions.
-
prod!
(r, A)¶ Multiply elements of
A
over the singleton dimensions ofr
, and write results tor
.
-
any
(itr) → Bool¶ Test whether any elements of a boolean collection are true.
-
any
(A, dims) Test whether any values along the given dimensions of an array are true.
-
any!
(r, A)¶ Test whether any values in
A
along the singleton dimensions ofr
are true, and write results tor
.
-
all
(itr) → Bool¶ Test whether all elements of a boolean collection are true.
-
all
(A, dims) Test whether all values along the given dimensions of an array are true.
-
all!
(r, A)¶ Test whether all values in
A
along the singleton dimensions ofr
are true, and write results tor
.
-
count
(p, itr) → Integer¶ Count the number of elements in
itr
for which predicatep
returns true.
-
any
(p, itr) → Bool Determine whether predicate
p
returns true for any elements ofitr
.
-
all
(p, itr) → Bool Determine whether predicate
p
returns true for all elements ofitr
.julia> all(i->(4<=i<=6), [4,5,6]) true
-
map
(f, c...) → collection¶ Transform collection
c
by applyingf
to each element. For multiple collection arguments, applyf
elementwise.julia> map((x) -> x * 2, [1, 2, 3]) 3-element Array{Int64,1}: 2 4 6 julia> map(+, [1, 2, 3], [10, 20, 30]) 3-element Array{Int64,1}: 11 22 33
-
map!
(function, collection)¶ In-place version of
map()
.
-
map!
(function, destination, collection...) Like
map()
, but stores the result indestination
rather than a new collection.destination
must be at least as large as the first collection.
-
mapreduce
(f, op, itr)¶ Applies function
f
to each element initr
and then reduces the result using the binary functionop
.julia> mapreduce(x->x^2, +, [1:3]) # == 1 + 4 + 9 14
The associativity of the reduction is implementation-dependent; if you need a particular associativity, e.g. left-to-right, you should write your own loop. See documentation for
reduce
.
-
first
(coll)¶ Get the first element of an iterable collection.
-
last
(coll)¶ Get the last element of an ordered collection, if it can be computed in O(1) time. This is accomplished by calling
endof
to get the last index.
-
step
(r)¶ Get the step size of a
Range
object.
-
collect
(collection)¶ Return an array of all items in a collection. For associative collections, returns (key, value) tuples.
-
collect
(element_type, collection) Return an array of type
Array{element_type,1}
of all items in a collection.
-
issubset
(a, b)¶ Determine whether every element of
a
is also inb
, using thein
function.
-
filter
(function, collection)¶ Return a copy of
collection
, removing elements for whichfunction
is false. For associative collections, the function is passed two arguments (key and value).
-
filter!
(function, collection)¶ Update
collection
, removing elements for whichfunction
is false. For associative collections, the function is passed two arguments (key and value).
Indexable Collections¶
-
getindex
(collection, key...)¶ Retrieve the value(s) stored at the given key or index within a collection. The syntax
a[i,j,...]
is converted by the compiler togetindex(a, i, j, ...)
.
-
setindex!
(collection, value, key...)¶ Store the given value at the given key or index within a collection. The syntax
a[i,j,...] = x
is converted by the compiler tosetindex!(a, x, i, j, ...)
.
Fully implemented by: Array
, DArray
, BitArray
, AbstractArray
, SubArray
, ObjectIdDict
, Dict
, WeakKeyDict
, String
.
Partially implemented by: Range
, Range1
, Tuple
.
Associative Collections¶
Dict
is the standard associative collection. Its implementation uses the hash(x)
as the hashing function for the key, and isequal(x,y)
to determine equality. Define these two functions for custom types to override how they are stored in a hash table.
ObjectIdDict
is a special hash table where the keys are always object identities. WeakKeyDict
is a hash table implementation where the keys are weak references to objects, and thus may be garbage collected even when referenced in a hash table.
Dicts can be created using a literal syntax: {"A"=>1, "B"=>2}
. Use of curly brackets will create a Dict
of type Dict{Any,Any}
. Use of square brackets will attempt to infer type information from the keys and values (i.e. ["A"=>1, "B"=>2]
creates a Dict{ASCIIString, Int64}
). To explicitly specify types use the syntax: (KeyType=>ValueType)[...]
. For example, (ASCIIString=>Int32)["A"=>1, "B"=>2]
.
As with arrays, Dicts
may be created with comprehensions. For example,
{i => f(i) for i = 1:10}
.
Given a dictionary D
, the syntax D[x]
returns the value of key x
(if it exists) or throws an error, and D[x] = y
stores the key-value pair x => y
in D
(replacing any existing value for the key x
). Multiple arguments to D[...]
are converted to tuples; for example, the syntax D[x,y]
is equivalent to D[(x,y)]
, i.e. it refers to the value keyed by the tuple (x,y)
.
-
Dict
()¶ Dict{K,V}()
constructs a hashtable with keys of type K and values of type V. The literal syntax is
{"A"=>1, "B"=>2}
for aDict{Any,Any}
, or["A"=>1, "B"=>2]
for aDict
of inferred type.
-
haskey
(collection, key) → Bool¶ Determine whether a collection has a mapping for a given key.
-
get
(collection, key, default)¶ Return the value stored for the given key, or the given default value if no mapping for the key is present.
-
get
(f::Function, collection, key) Return the value stored for the given key, or if no mapping for the key is present, return
f()
. Useget!
to also store the default value in the dictionary.This is intended to be called using
do
block syntax:get(dict, key) do # default value calculated here time() end
-
get!
(collection, key, default)¶ Return the value stored for the given key, or if no mapping for the key is present, store
key => default
, and returndefault
.
-
get!
(f::Function, collection, key) Return the value stored for the given key, or if no mapping for the key is present, store
key => f()
, and returnf()
.This is intended to be called using
do
block syntax:get!(dict, key) do # default value calculated here time() end
-
getkey
(collection, key, default)¶ Return the key matching argument
key
if one exists incollection
, otherwise returndefault
.
-
delete!
(collection, key)¶ Delete the mapping for the given key in a collection, and return the colection.
-
pop!
(collection, key[, default])¶ Delete and return the mapping for
key
if it exists incollection
, otherwise returndefault
, or throw an error if default is not specified.
-
keys
(collection)¶ Return an iterator over all keys in a collection.
collect(keys(d))
returns an array of keys.
-
values
(collection)¶ Return an iterator over all values in a collection.
collect(values(d))
returns an array of values.
-
merge
(collection, others...)¶ Construct a merged collection from the given collections.
-
merge!
(collection, others...)¶ Update collection with pairs from the other collections
-
sizehint
(s, n)¶ Suggest that collection
s
reserve capacity for at leastn
elements. This can improve performance.
Fully implemented by: ObjectIdDict
, Dict
, WeakKeyDict
.
Partially implemented by: IntSet
, Set
, EnvHash
, Array
, BitArray
.
Set-Like Collections¶
-
Set
([itr])¶ Construct a
Set
of the values generated by the given iterable object, or an empty set. Should be used instead ofIntSet
for sparse integer sets, or for sets of arbitrary objects.
-
IntSet
([itr])¶ Construct a sorted set of the integers generated by the given iterable object, or an empty set. Implemented as a bit string, and therefore designed for dense integer sets. Only non-negative integers can be stored. If the set will be sparse (for example holding a single very large integer), use
Set
instead.
-
union
(s1, s2...)¶ Construct the union of two or more sets. Maintains order with arrays.
-
union!
(s, iterable)¶ Union each element of
iterable
into sets
in-place.
-
intersect
(s1, s2...)¶ Construct the intersection of two or more sets. Maintains order and multiplicity of the first argument for arrays and ranges.
-
setdiff
(s1, s2)¶ Construct the set of elements in
s1
but nots2
. Maintains order with arrays. Note that both arguments must be collections, and both will be iterated over. In particular,setdiff(set,element)
whereelement
is a potential member ofset
, will not work in general.
-
setdiff!
(s, iterable)¶ Remove each element of
iterable
from sets
in-place.
-
symdiff
(s1, s2...)¶ Construct the symmetric difference of elements in the passed in sets or arrays. Maintains order with arrays.
-
symdiff!
(s, n)¶ IntSet s is destructively modified to toggle the inclusion of integer
n
.
-
symdiff!
(s, itr) For each element in
itr
, destructively toggle its inclusion in sets
.
-
symdiff!
(s1, s2) Construct the symmetric difference of IntSets
s1
ands2
, storing the result ins1
.
-
complement
(s)¶ Returns the set-complement of IntSet
s
.
-
complement!
(s)¶ Mutates IntSet
s
into its set-complement.
-
intersect!
(s1, s2)¶ Intersects IntSets
s1
ands2
and overwrites the sets1
with the result. If needed, s1 will be expanded to the size ofs2
.
-
issubset
(A, S) → Bool True if
A ⊆ S
(A is a subset of or equal to S)
Fully implemented by: IntSet
, Set
.
Partially implemented by: Array
.
Dequeues¶
-
push!
(collection, items...) → collection¶ Insert items at the end of a collection.
-
pop!
(collection) → item Remove the last item in a collection and return it.
-
unshift!
(collection, items...) → collection¶ Insert items at the beginning of a collection.
-
shift!
(collection) → item¶ Remove the first item in a collection.
-
insert!
(collection, index, item)¶ Insert an item at the given index.
-
deleteat!
(collection, index)¶ Remove the item at the given index, and return the modified collection. Subsequent items are shifted to fill the resulting gap.
-
deleteat!
(collection, itr) Remove the items at the indices given by
itr
, and return the modified collection. Subsequent items are shifted to fill the resulting gap.itr
must be sorted and unique.
-
splice!
(collection, index[, replacement]) → item¶ Remove the item at the given index, and return the removed item. Subsequent items are shifted down to fill the resulting gap. If specified, replacement values from an ordered collection will be spliced in place of the removed item.
To insert
replacement
before an indexn
without removing any items, usesplice(collection, n-1:n, replacement)
.
-
splice!
(collection, range[, replacement]) → items Remove items in the specified index range, and return a collection containing the removed items. Subsequent items are shifted down to fill the resulting gap. If specified, replacement values from an ordered collection will be spliced in place of the removed items.
To insert
replacement
before an indexn
without removing any items, usesplice(collection, n-1:n, replacement)
.
-
resize!
(collection, n) → collection¶ Resize collection to contain
n
elements.
-
append!
(collection, items) → collection.¶ Add the elements of
items
to the end of a collection.julia> append!([1],[2,3]) 3-element Array{Int64,1}: 1 2 3
-
prepend!
(collection, items) → collection¶ Insert the elements of
items
to the beginning of a collection.julia> prepend!([3],[1,2]) 3-element Array{Int64,1}: 1 2 3
Fully implemented by: Vector
(aka 1-d Array
), BitVector
(aka 1-d BitArray
).
Strings¶
-
length
(s) The number of characters in string
s
.
-
sizeof
(s::String) The number of bytes in string
s
.
-
*
(s, t)¶ Concatenate strings. The
*
operator is an alias to this function.julia> "Hello " * "world" "Hello world"
-
^
(s, n)¶ Repeat
n
times the strings
. The^
operator is an alias to this function.julia> "Test "^3 "Test Test Test "
-
string
(xs...)¶ Create a string from any values using the
print
function.
-
repr
(x)¶ Create a string from any value using the
showall
function.
-
bytestring
(::Ptr{Uint8}[, length])¶ Create a string from the address of a C (0-terminated) string encoded in ASCII or UTF-8. A copy is made; the ptr can be safely freed. If
length
is specified, the string does not have to be 0-terminated.
-
bytestring
(s) Convert a string to a contiguous byte array representation appropriate for passing it to C functions. The string will be encoded as either ASCII or UTF-8.
-
ascii
(::Array{Uint8, 1})¶ Create an ASCII string from a byte array.
-
ascii
(s) Convert a string to a contiguous ASCII string (all characters must be valid ASCII characters).
-
utf8
(::Array{Uint8, 1})¶ Create a UTF-8 string from a byte array.
-
utf8
(s) Convert a string to a contiguous UTF-8 string (all characters must be valid UTF-8 characters).
-
normalize_string
(s, normalform::Symbol)¶ Normalize the string
s
according to one of the four “normal forms” of the Unicode standard:normalform
can be:NFC
,:NFD
,:NFKC
, or:NFKD
. Normal forms C (canonical composition) and D (canonical decomposition) convert different visually identical representations of the same abstract string into a single canonical form, with form C being more compact. Normal forms KC and KD additionally canonicalize “compatibility equivalents”: they convert characters that are abstractly similar but visually distinct into a single canonical choice (e.g. they expand ligatures into the individual characters), with form KC being more compact.Alternatively, finer control and additional transformations may be be obtained by calling normalize_string(s; keywords...), where any number of the following boolean keywords options (which all default to
false
except forcompose
) are specified:compose=false
: do not perform canonical compositiondecompose=true
: do canonical decomposition instead of canonical composition (compose=true
is ignored if present)compat=true
: compatibility equivalents are canonicalizedcasefold=true
: perform Unicode case folding, e.g. for case-insensitive string comparisonnewline2lf=true
,newline2ls=true
, ornewline2ps=true
: convert various newline sequences (LF, CRLF, CR, NEL) into a linefeed (LF), line-separation (LS), or paragraph-separation (PS) character, respectivelystripmark=true
: strip diacritical marks (e.g. accents)stripignore=true
: strip Unicode’s “default ignorable” characters (e.g. the soft hyphen or the left-to-right marker)stripcc=true
: strip control characters; horizontal tabs and form feeds are converted to spaces; newlines are also converted to spaces unless a newline-conversion flag was specifiedrejectna=true
: throw an error if unassigned code points are foundstable=true
: enforce Unicode Versioning Stability
For example, NFKC corresponds to the options
compose=true, compat=true, stable=true
.
-
is_valid_ascii
(s) → Bool¶ Returns true if the string or byte vector is valid ASCII, false otherwise.
-
is_valid_utf8
(s) → Bool¶ Returns true if the string or byte vector is valid UTF-8, false otherwise.
-
is_valid_char
(c) → Bool¶ Returns true if the given char or integer is a valid Unicode code point.
-
is_assigned_char
(c) → Bool¶ Returns true if the given char or integer is an assigned Unicode code point.
-
ismatch
(r::Regex, s::String) → Bool¶ Test whether a string contains a match of the given regular expression.
-
match
(r::Regex, s::String[, idx::Integer[, addopts]])¶ Search for the first match of the regular expression
r
ins
and return a RegexMatch object containing the match, or nothing if the match failed. The matching substring can be retrieved by accessingm.match
and the captured sequences can be retrieved by accessingm.captures
The optionalidx
argument specifies an index at which to start the search.
-
eachmatch
(r::Regex, s::String[, overlap::Bool=false])¶ Search for all matches of a the regular expression
r
ins
and return a iterator over the matches. If overlap is true, the matching sequences are allowed to overlap indices in the original string, otherwise they must be from distinct character ranges.
-
matchall
(r::Regex, s::String[, overlap::Bool=false]) → Vector{String}¶ Return a vector of the matching substrings from eachmatch.
-
lpad
(string, n, p)¶ Make a string at least
n
characters long by padding on the left with copies ofp
.
-
rpad
(string, n, p)¶ Make a string at least
n
characters long by padding on the right with copies ofp
.
-
search
(string, chars[, start])¶ Search for the first occurance of the given characters within the given string. The second argument may be a single character, a vector or a set of characters, a string, or a regular expression (though regular expressions are only allowed on contiguous strings, such as ASCII or UTF-8 strings). The third argument optionally specifies a starting index. The return value is a range of indexes where the matching sequence is found, such that
s[search(s,x)] == x
:search(string, "substring")
=start:end
such thatstring[start:end] == "substring"
, or0:-1
if unmatched.search(string, 'c')
=index
such thatstring[index] == 'c'
, or0
if unmatched.
-
rsearch
(string, chars[, start])¶ Similar to
search
, but returning the last occurance of the given characters within the given string, searching in reverse fromstart
.
-
searchindex
(string, substring[, start])¶ Similar to
search
, but return only the start index at which the substring is found, or 0 if it is not.
-
rsearchindex
(string, substring[, start])¶ Similar to
rsearch
, but return only the start index at which the substring is found, or 0 if it is not.
-
contains
(haystack, needle)¶ Determine whether the second argument is a substring of the first.
-
replace
(string, pat, r[, n])¶ Search for the given pattern
pat
, and replace each occurrence withr
. Ifn
is provided, replace at mostn
occurrences. As with search, the second argument may be a single character, a vector or a set of characters, a string, or a regular expression. Ifr
is a function, each occurrence is replaced withr(s)
wheres
is the matched substring.
-
split
(string, [chars, [limit,] [include_empty]])¶ Return an array of substrings by splitting the given string on occurrences of the given character delimiters, which may be specified in any of the formats allowed by
search
‘s second argument (i.e. a single character, collection of characters, string, or regular expression). Ifchars
is omitted, it defaults to the set of all space characters, andinclude_empty
is taken to be false. The last two arguments are also optional: they are are a maximum size for the result and a flag determining whether empty fields should be included in the result.
-
rsplit
(string, [chars, [limit,] [include_empty]])¶ Similar to
split
, but starting from the end of the string.
-
strip
(string[, chars])¶ Return
string
with any leading and trailing whitespace removed. Ifchars
(a character, or vector or set of characters) is provided, instead remove characters contained in it.
-
lstrip
(string[, chars])¶ Return
string
with any leading whitespace removed. Ifchars
(a character, or vector or set of characters) is provided, instead remove characters contained in it.
-
rstrip
(string[, chars])¶ Return
string
with any trailing whitespace removed. Ifchars
(a character, or vector or set of characters) is provided, instead remove characters contained in it.
-
beginswith
(string, prefix | chars)¶ Returns
true
ifstring
starts withprefix
. If the second argument is a vector or set of characters, tests whether the first character ofstring
belongs to that set.
-
endswith
(string, suffix | chars)¶ Returns
true
ifstring
ends withsuffix
. If the second argument is a vector or set of characters, tests whether the last character ofstring
belongs to that set.
-
uppercase
(string)¶ Returns
string
with all characters converted to uppercase.
-
lowercase
(string)¶ Returns
string
with all characters converted to lowercase.
-
ucfirst
(string)¶ Returns
string
with the first character converted to uppercase.
-
lcfirst
(string)¶ Returns
string
with the first character converted to lowercase.
-
join
(strings, delim)¶ Join an array of strings into a single string, inserting the given delimiter between adjacent strings.
-
chop
(string)¶ Remove the last character from a string
-
chomp
(string)¶ Remove a trailing newline from a string
-
ind2chr
(string, i)¶ Convert a byte index to a character index
-
chr2ind
(string, i)¶ Convert a character index to a byte index
-
isvalid
(str, i)¶ Tells whether index
i
is valid for the given string
-
nextind
(str, i)¶ Get the next valid string index after
i
. Returns a value greater thanendof(str)
at or after the end of the string.
-
prevind
(str, i)¶ Get the previous valid string index before
i
. Returns a value less than1
at the beginning of the string.
-
randstring
(len)¶ Create a random ASCII string of length
len
, consisting of upper- and lower-case letters and the digits 0-9
-
charwidth
(c)¶ Gives the number of columns needed to print a character.
-
strwidth
(s)¶ Gives the number of columns needed to print a string.
-
isalnum
(c::Union(Char, String)) → Bool¶ Tests whether a character is alphanumeric, or whether this is true for all elements of a string.
-
isalpha
(c::Union(Char, String)) → Bool¶ Tests whether a character is alphabetic, or whether this is true for all elements of a string.
-
isascii
(c::Union(Char, String)) → Bool¶ Tests whether a character belongs to the ASCII character set, or whether this is true for all elements of a string.
-
isblank
(c::Union(Char, String)) → Bool¶ Tests whether a character is a tab or space, or whether this is true for all elements of a string.
-
iscntrl
(c::Union(Char, String)) → Bool¶ Tests whether a character is a control character, or whether this is true for all elements of a string.
-
isdigit
(c::Union(Char, String)) → Bool¶ Tests whether a character is a numeric digit (0-9), or whether this is true for all elements of a string.
-
isgraph
(c::Union(Char, String)) → Bool¶ Tests whether a character is printable, and not a space, or whether this is true for all elements of a string.
-
islower
(c::Union(Char, String)) → Bool¶ Tests whether a character is a lowercase letter, or whether this is true for all elements of a string.
-
isprint
(c::Union(Char, String)) → Bool¶ Tests whether a character is printable, including space, or whether this is true for all elements of a string.
-
ispunct
(c::Union(Char, String)) → Bool¶ Tests whether a character is printable, and not a space or alphanumeric, or whether this is true for all elements of a string.
-
isspace
(c::Union(Char, String)) → Bool¶ Tests whether a character is any whitespace character, or whether this is true for all elements of a string.
-
isupper
(c::Union(Char, String)) → Bool¶ Tests whether a character is an uppercase letter, or whether this is true for all elements of a string.
-
isxdigit
(c::Union(Char, String)) → Bool¶ Tests whether a character is a valid hexadecimal digit, or whether this is true for all elements of a string.
-
symbol
(str) → Symbol¶ Convert a string to a
Symbol
.
-
escape_string
(str::String) → String¶ General escaping of traditional C and Unicode escape sequences. See
print_escaped()
for more general escaping.
-
unescape_string
(s::String) → String¶ General unescaping of traditional C and Unicode escape sequences. Reverse of
escape_string()
. See alsoprint_unescaped()
.
-
utf16
(s)¶ Create a UTF-16 string from a byte array, array of
Uint16
, or any other string type. (Data must be valid UTF-16. Conversions of byte arrays check for a byte-order marker in the first two bytes, and do not include it in the resulting string.)Note that the resulting
UTF16String
data is terminated by the NUL codepoint (16-bit zero), which is not treated as a character in the string (so that it is mostly invisible in Julia); this allows the string to be passed directly to external functions requiring NUL-terminated data. This NUL is appended automatically by the utf16(s) conversion function. If you have aUint16
arrayA
that is already NUL-terminated valid UTF-16 data, then you can instead use UTF16String(A)` to construct the string without making a copy of the data and treating the NUL as a terminator rather than as part of the string.
-
utf16
(::Union(Ptr{Uint16}, Ptr{Int16})[, length]) Create a string from the address of a NUL-terminated UTF-16 string. A copy is made; the pointer can be safely freed. If
length
is specified, the string does not have to be NUL-terminated.
-
is_valid_utf16
(s) → Bool¶ Returns true if the string or
Uint16
array is valid UTF-16.
-
utf32
(s)¶ Create a UTF-32 string from a byte array, array of
Uint32
, or any other string type. (Conversions of byte arrays check for a byte-order marker in the first four bytes, and do not include it in the resulting string.)Note that the resulting
UTF32String
data is terminated by the NUL codepoint (32-bit zero), which is not treated as a character in the string (so that it is mostly invisible in Julia); this allows the string to be passed directly to external functions requiring NUL-terminated data. This NUL is appended automatically by the utf32(s) conversion function. If you have aUint32
arrayA
that is already NUL-terminated UTF-32 data, then you can instead use UTF32String(A)` to construct the string without making a copy of the data and treating the NUL as a terminator rather than as part of the string.
-
utf32
(::Union(Ptr{Char}, Ptr{Uint32}, Ptr{Int32})[, length]) Create a string from the address of a NUL-terminated UTF-32 string. A copy is made; the pointer can be safely freed. If
length
is specified, the string does not have to be NUL-terminated.
-
wstring
(s)¶ This is a synonym for either
utf32(s)
orutf16(s)
, depending on whetherCwchar_t
is 32 or 16 bits, respectively. The synonymWString
forUTF32String
orUTF16String
is also provided.
I/O¶
-
STDOUT
¶ Global variable referring to the standard out stream.
-
STDERR
¶ Global variable referring to the standard error stream.
-
STDIN
¶ Global variable referring to the standard input stream.
-
open
(file_name[, read, write, create, truncate, append]) → IOStream¶ Open a file in a mode specified by five boolean arguments. The default is to open files for reading only. Returns a stream for accessing the file.
-
open
(file_name[, mode]) → IOStream Alternate syntax for open, where a string-based mode specifier is used instead of the five booleans. The values of
mode
correspond to those fromfopen(3)
or Perlopen
, and are equivalent to setting the following boolean groups:r read r+ read, write w write, create, truncate w+ read, write, create, truncate a write, create, append a+ read, write, create, append
-
open
(f::function, args...) Apply the function
f
to the result ofopen(args...)
and close the resulting file descriptor upon completion.Example:
open(readall, "file.txt")
-
IOBuffer
() → IOBuffer¶ Create an in-memory I/O stream.
-
IOBuffer
(size::Int) Create a fixed size IOBuffer. The buffer will not grow dynamically.
-
IOBuffer
(string) Create a read-only IOBuffer on the data underlying the given string
-
IOBuffer
([data][, readable, writable[, maxsize]]) Create an IOBuffer, which may optionally operate on a pre-existing array. If the readable/writable arguments are given, they restrict whether or not the buffer may be read from or written to respectively. By default the buffer is readable but not writable. The last argument optionally specifies a size beyond which the buffer may not be grown.
-
takebuf_array
(b::IOBuffer)¶ Obtain the contents of an
IOBuffer
as an array, without copying.
-
takebuf_string
(b::IOBuffer)¶ Obtain the contents of an
IOBuffer
as a string, without copying.
-
fdio
([name::String, ]fd::Integer[, own::Bool]) → IOStream¶ Create an
IOStream
object from an integer file descriptor. Ifown
is true, closing this object will close the underlying descriptor. By default, anIOStream
is closed when it is garbage collected.name
allows you to associate the descriptor with a named file.
-
flush
(stream)¶ Commit all currently buffered writes to the given stream.
-
flush_cstdio
()¶ Flushes the C
stdout
andstderr
streams (which may have been written to by external C code).
-
close
(stream)¶ Close an I/O stream. Performs a
flush
first.
-
write
(stream, x)¶ Write the canonical binary representation of a value to the given stream.
-
read
(stream, type)¶ Read a value of the given type from a stream, in canonical binary representation.
-
read
(stream, type, dims) Read a series of values of the given type from a stream, in canonical binary representation.
dims
is either a tuple or a series of integer arguments specifying the size ofArray
to return.
-
read!
(stream, array::Array)¶ Read binary data from a stream, filling in the argument
array
.
-
readbytes!
(stream, b::Vector{Uint8}, nb=length(b))¶ Read at most
nb
bytes from the stream intob
, returning the number of bytes read (increasing the size ofb
as needed).
-
readbytes
(stream, nb=typemax(Int))¶ Read at most
nb
bytes from the stream, returning aVector{Uint8}
of the bytes read.
-
position
(s)¶ Get the current position of a stream.
-
seek
(s, pos)¶ Seek a stream to the given position.
-
seekstart
(s)¶ Seek a stream to its beginning.
-
seekend
(s)¶ Seek a stream to its end.
-
skip
(s, offset)¶ Seek a stream relative to the current position.
-
mark
(s)¶ Add a mark at the current position of stream
s
. Returns the marked position.See also
unmark()
,reset()
,ismarked()
-
unmark
(s)¶ Remove a mark from stream
s
. Returnstrue
if the stream was marked,false
otherwise.See also
mark()
,reset()
,ismarked()
-
reset
(s)¶ Reset a stream
s
to a previously marked position, and remove the mark. Returns the previously marked position. Throws an error if the stream is not marked.See also
mark()
,unmark()
,ismarked()
-
ismarked
(s)¶ Returns true if stream
s
is marked.See also
mark()
,unmark()
,reset()
-
eof
(stream) → Bool¶ Tests whether an I/O stream is at end-of-file. If the stream is not yet exhausted, this function will block to wait for more data if necessary, and then return
false
. Therefore it is always safe to read one byte after seeingeof
returnfalse
.eof
will returnfalse
as long as buffered data is still available, even if the remote end of a connection is closed.
-
isreadonly
(stream) → Bool¶ Determine whether a stream is read-only.
-
isopen
(stream) → Bool¶ Determine whether a stream is open (i.e. has not been closed yet). If the connection has been closed remotely (in case of e.g. a socket),
isopen
will returnfalse
even though buffered data may still be available. Useeof
to check if necessary.
-
ntoh
(x)¶ Converts the endianness of a value from Network byte order (big-endian) to that used by the Host.
-
hton
(x)¶ Converts the endianness of a value from that used by the Host to Network byte order (big-endian).
-
ltoh
(x)¶ Converts the endianness of a value from Little-endian to that used by the Host.
-
htol
(x)¶ Converts the endianness of a value from that used by the Host to Little-endian.
-
ENDIAN_BOM
¶ The 32-bit byte-order-mark indicates the native byte order of the host machine. Little-endian machines will contain the value 0x04030201. Big-endian machines will contain the value 0x01020304.
-
serialize
(stream, value)¶ Write an arbitrary value to a stream in an opaque format, such that it can be read back by
deserialize
. The read-back value will be as identical as possible to the original. In general, this process will not work if the reading and writing are done by different versions of Julia, or an instance of Julia with a different system image.
-
deserialize
(stream)¶ Read a value written by
serialize
.
-
print_escaped
(io, str::String, esc::String)¶ General escaping of traditional C and Unicode escape sequences, plus any characters in esc are also escaped (with a backslash).
-
print_unescaped
(io, s::String)¶ General unescaping of traditional C and Unicode escape sequences. Reverse of
print_escaped()
.
-
print_joined
(io, items, delim[, last])¶ Print elements of
items
toio
withdelim
between them. Iflast
is specified, it is used as the final delimiter instead ofdelim
.
-
print_shortest
(io, x)¶ Print the shortest possible representation of number
x
as a floating point number, ensuring that it would parse to the exact same number.
-
fd
(stream)¶ Returns the file descriptor backing the stream or file. Note that this function only applies to synchronous File‘s and IOStream‘s not to any of the asynchronous streams.
-
redirect_stdout
()¶ Create a pipe to which all C and Julia level STDOUT output will be redirected. Returns a tuple (rd,wr) representing the pipe ends. Data written to STDOUT may now be read from the rd end of the pipe. The wr end is given for convenience in case the old STDOUT object was cached by the user and needs to be replaced elsewhere.
-
redirect_stdout
(stream) Replace STDOUT by stream for all C and julia level output to STDOUT. Note that stream must be a TTY, a Pipe or a TcpSocket.
-
redirect_stderr
([stream])¶ Like redirect_stdout, but for STDERR
-
redirect_stdin
([stream])¶ Like redirect_stdout, but for STDIN. Note that the order of the return tuple is still (rd,wr), i.e. data to be read from STDIN, may be written to wr.
-
readchomp
(x)¶ Read the entirety of x as a string but remove trailing newlines. Equivalent to chomp(readall(x)).
-
readdir
([dir]) → Vector{ByteString}¶ Returns the files and directories in the directory dir (or the current working directory if not given).
-
truncate
(file, n)¶ Resize the file or buffer given by the first argument to exactly n bytes, filling previously unallocated space with ‘0’ if the file or buffer is grown
-
skipchars
(stream, predicate; linecomment::Char)¶ Advance the stream until before the first character for which
predicate
returns false. For exampleskipchars(stream, isspace)
will skip all whitespace. If keyword argumentlinecomment
is specified, characters from that character through the end of a line will also be skipped.
-
countlines
(io[, eol::Char])¶ Read io until the end of the stream/file and count the number of non-empty lines. To specify a file pass the filename as the first argument. EOL markers other than ‘n’ are supported by passing them as the second argument.
-
PipeBuffer
()¶ An IOBuffer that allows reading and performs writes by appending. Seeking and truncating are not supported. See IOBuffer for the available constructors.
-
PipeBuffer
(data::Vector{Uint8}[, maxsize]) Create a PipeBuffer to operate on a data vector, optionally specifying a size beyond which the underlying Array may not be grown.
-
readavailable
(stream)¶ Read all available data on the stream, blocking the task only if no data is available.
-
stat
(file)¶ Returns a structure whose fields contain information about the file. The fields of the structure are:
size The size (in bytes) of the file device ID of the device that contains the file inode The inode number of the file mode The protection mode of the file nlink The number of hard links to the file uid The user id of the owner of the file gid The group id of the file owner rdev If this file refers to a device, the ID of the device it refers to blksize The file-system preffered block size for the file blocks The number of such blocks allocated mtime Unix timestamp of when the file was last modified ctime Unix timestamp of when the file was created
-
lstat
(file)¶ Like stat, but for symbolic links gets the info for the link itself rather than the file it refers to. This function must be called on a file path rather than a file object or a file descriptor.
-
ctime
(file)¶ Equivalent to stat(file).ctime
-
mtime
(file)¶ Equivalent to stat(file).mtime
-
filemode
(file)¶ Equivalent to stat(file).mode
-
filesize
(path...)¶ Equivalent to stat(file).size
-
uperm
(file)¶ Gets the permissions of the owner of the file as a bitfield of
01 Execute Permission 02 Write Permission 04 Read Permission For allowed arguments, see
stat
.
-
gperm
(file)¶ Like uperm but gets the permissions of the group owning the file
-
operm
(file)¶ Like uperm but gets the permissions for people who neither own the file nor are a member of the group owning the file
-
cp
(src::String, dst::String)¶ Copy a file from src to dest.
-
download
(url[, localfile])¶ Download a file from the given url, optionally renaming it to the given local file name. Note that this function relies on the availability of external tools such as
curl
,wget
orfetch
to download the file and is provided for convenience. For production use or situations in which more options are need, please use a package that provides the desired functionality instead.
-
mv
(src::String, dst::String)¶ Move a file from src to dst.
-
rm
(path::String; recursive=false)¶ Delete the file, link, or empty directory at the given path. If
recursive=true
is passed and the path is a directory, then all contents are removed recursively.
-
touch
(path::String)¶ Update the last-modified timestamp on a file to the current time.
Network I/O¶
-
connect
([host, ]port) → TcpSocket¶ Connect to the host
host
on portport
-
connect
(path) → Pipe Connect to the Named Pipe/Domain Socket at
path
-
listen
([addr, ]port) → TcpServer¶ Listen on port on the address specified by
addr
. By default this listens on localhost only. To listen on all interfaces pass,IPv4(0)
orIPv6(0)
as appropriate.
-
listen
(path) → PipeServer Listens on/Creates a Named Pipe/Domain Socket
-
getaddrinfo
(host)¶ Gets the IP address of the
host
(may have to do a DNS lookup)
-
parseip
(addr)¶ Parse a string specifying an IPv4 or IPv6 ip address.
-
IPv4
(host::Integer) → IPv4¶ Returns IPv4 object from ip address formatted as Integer
-
IPv6
(host::Integer) → IPv6¶ Returns IPv6 object from ip address formatted as Integer
-
nb_available
(stream)¶ Returns the number of bytes available for reading before a read from this stream or buffer will block.
-
accept
(server[, client])¶ Accepts a connection on the given server and returns a connection to the client. An uninitialized client stream may be provided, in which case it will be used instead of creating a new stream.
-
listenany
(port_hint) -> (Uint16, TcpServer)¶ Create a TcpServer on any port, using hint as a starting point. Returns a tuple of the actual port that the server was created on and the server itself.
-
watch_file
(cb=false, s; poll=false)¶ Watch file or directory
s
and run callbackcb
whens
is modified. Thepoll
parameter specifies whether to use file system event monitoring or polling. The callback functioncb
should accept 3 arguments:(filename, events, status)
wherefilename
is the name of file that was modified,events
is an object with boolean fieldschanged
andrenamed
when using file system event monitoring, orreadable
andwritable
when using polling, andstatus
is always 0. Passfalse
forcb
to not use a callback function.
-
poll_fd
(fd, seconds::Real; readable=false, writable=false)¶ Poll a file descriptor fd for changes in the read or write availability and with a timeout given by the second argument. If the timeout is not needed, use
wait(fd)
instead. The keyword arguments determine which of read and/or write status should be monitored and at least one of them needs to be set to true. The returned value is an object with boolean fieldsreadable
,writable
, andtimedout
, giving the result of the polling.
-
poll_file
(s, interval_seconds::Real, seconds::Real)¶ Monitor a file for changes by polling every interval_seconds seconds for seconds seconds. A return value of true indicates the file changed, a return value of false indicates a timeout.
Text I/O¶
-
show
(x)¶ Write an informative text representation of a value to the current output stream. New types should overload
show(io, x)
where the first argument is a stream. The representation used byshow
generally includes Julia-specific formatting and type information.
-
showcompact
(x)¶ Show a more compact representation of a value. This is used for printing array elements. If a new type has a different compact representation, it should overload
showcompact(io, x)
where the first argument is a stream.
-
showall
(x)¶ Similar to
show
, except shows all elements of arrays.
-
summary
(x)¶ Return a string giving a brief description of a value. By default returns
string(typeof(x))
. For arrays, returns strings like “2x2 Float64 Array”.
-
print
(x)¶ Write (to the default output stream) a canonical (un-decorated) text representation of a value if there is one, otherwise call
show
. The representation used byprint
includes minimal formatting and tries to avoid Julia-specific details.
-
println
(x)¶ Print (using
print()
)x
followed by a newline.
-
print_with_color
(color::Symbol, [io, ]strings...)¶ Print strings in a color specified as a symbol, for example
:red
or:blue
.
-
info
(msg)¶ Display an informational message.
-
warn
(msg)¶ Display a warning.
-
@printf
([io::IOStream, ]"%Fmt", args...)¶ Print arg(s) using C
printf()
style format specification string. Optionally, an IOStream may be passed as the first argument to redirect output.
-
@sprintf
("%Fmt", args...)¶ Return
@printf
formatted output as string.
-
sprint
(f::Function, args...)¶ Call the given function with an I/O stream and the supplied extra arguments. Everything written to this I/O stream is returned as a string.
-
showerror
(io, e)¶ Show a descriptive representation of an exception object.
-
dump
(x)¶ Show all user-visible structure of a value.
-
xdump
(x)¶ Show all structure of a value, including all fields of objects.
-
readall
(stream)¶ Read the entire contents of an I/O stream as a string.
-
readline
(stream=STDIN)¶ Read a single line of text, including a trailing newline character (if one is reached before the end of the input), from the given
stream
(defaults toSTDIN
),
-
readuntil
(stream, delim)¶ Read a string, up to and including the given delimiter byte.
-
readlines
(stream)¶ Read all lines as an array.
-
eachline
(stream)¶ Create an iterable object that will yield each line from a stream.
-
readdlm
(source, delim::Char, T::Type, eol::Char; header=false, skipstart=0, use_mmap, ignore_invalid_chars=false, quotes=true, dims, comments=true, comment_char='#')¶ Read a matrix from the source where each line (separated by
eol
) gives one row, with elements separated by the given delimeter. The source can be a text file, stream or byte array. Memory mapped files can be used by passing the byte array representation of the mapped segment as source.If
T
is a numeric type, the result is an array of that type, with any non-numeric elements asNaN
for floating-point types, or zero. Other useful values ofT
includeASCIIString
,String
, andAny
.If
header
istrue
, the first row of data will be read as header and the tuple(data_cells, header_cells)
is returned instead of onlydata_cells
.Specifying
skipstart
will ignore the corresponding number of initial lines from the input.If
use_mmap
istrue
, the file specified bysource
is memory mapped for potential speedups. Default istrue
except on Windows. On Windows, you may want to specifytrue
if the file is large, and is only read once and not written to.If
ignore_invalid_chars
istrue
, bytes insource
with invalid character encoding will be ignored. Otherwise an error is thrown indicating the offending character position.If
quotes
istrue
, column enclosed within double-quote (``) characters are allowed to contain new lines and column delimiters. Double-quote characters within a quoted field must be escaped with another double-quote.Specifying
dims
as a tuple of the expected rows and columns (including header, if any) may speed up reading of large files.If
comments
istrue
, lines beginning withcomment_char
and text followingcomment_char
in any line are ignored.
-
readdlm
(source, delim::Char, eol::Char; options...) If all data is numeric, the result will be a numeric array. If some elements cannot be parsed as numbers, a cell array of numbers and strings is returned.
-
readdlm
(source, delim::Char, T::Type; options...) The end of line delimiter is taken as
\n
.
-
readdlm
(source, delim::Char; options...) The end of line delimiter is taken as
\n
. If all data is numeric, the result will be a numeric array. If some elements cannot be parsed as numbers, a cell array of numbers and strings is returned.
-
readdlm
(source, T::Type; options...) The columns are assumed to be separated by one or more whitespaces. The end of line delimiter is taken as
\n
.
-
readdlm
(source; options...) The columns are assumed to be separated by one or more whitespaces. The end of line delimiter is taken as
\n
. If all data is numeric, the result will be a numeric array. If some elements cannot be parsed as numbers, a cell array of numbers and strings is returned.
-
writedlm
(f, A, delim='t')¶ Write
A
(either an array type or an iterable collection of iterable rows) as text tof
(either a filename string or anIO
stream) using the given delimeterdelim
(which defaults to tab, but can be any printable Julia object, typically aChar
orString
).For example, two vectors
x
andy
of the same length can be written as two columns of tab-delimited text tof
by eitherwritedlm(f, [x y])
or bywritedlm(f, zip(x, y))
.
-
readcsv
(source, [T::Type]; options...)¶ Equivalent to
readdlm
withdelim
set to comma.
-
writecsv
(filename, A)¶ Equivalent to
writedlm
withdelim
set to comma.
-
Base64Pipe
(ostream)¶ Returns a new write-only I/O stream, which converts any bytes written to it into base64-encoded ASCII bytes written to
ostream
. Callingclose
on theBase64Pipe
stream is necessary to complete the encoding (but does not closeostream
).
-
base64
(writefunc, args...)¶ -
base64
(args...) Given a
write
-like functionwritefunc
, which takes an I/O stream as its first argument,base64(writefunc, args...)
callswritefunc
to writeargs...
to a base64-encoded string, and returns the string.base64(args...)
is equivalent tobase64(write, args...)
: it converts its arguments into bytes using the standardwrite
functions and returns the base64-encoded string.
Multimedia I/O¶
Just as text output is performed by print
and user-defined types
can indicate their textual representation by overloading show
,
Julia provides a standardized mechanism for rich multimedia output
(such as images, formatted text, or even audio and video), consisting
of three parts:
- A function
display(x)
to request the richest available multimedia display of a Julia objectx
(with a plain-text fallback). - Overloading
writemime
allows one to indicate arbitrary multimedia representations (keyed by standard MIME types) of user-defined types. - Multimedia-capable display backends may be registered by subclassing
a generic
Display
type and pushing them onto a stack of display backends viapushdisplay
.
The base Julia runtime provides only plain-text display, but richer displays may be enabled by loading external modules or by using graphical Julia environments (such as the IPython-based IJulia notebook).
-
display
(x)¶ -
display
(d::Display, x) -
display
(mime, x) -
display
(d::Display, mime, x) Display
x
using the topmost applicable display in the display stack, typically using the richest supported multimedia output forx
, with plain-textSTDOUT
output as a fallback. Thedisplay(d, x)
variant attempts to displayx
on the given displayd
only, throwing aMethodError
ifd
cannot display objects of this type.There are also two variants with a
mime
argument (a MIME type string, such as"image/png"
), which attempt to displayx
using the requesed MIME type only, throwing aMethodError
if this type is not supported by either the display(s) or byx
. With these variants, one can also supply the “raw” data in the requested MIME type by passingx::String
(for MIME types with text-based storage, such as text/html or application/postscript) orx::Vector{Uint8}
(for binary MIME types).
-
redisplay
(x)¶ -
redisplay
(d::Display, x) -
redisplay
(mime, x) -
redisplay
(d::Display, mime, x) By default, the
redisplay
functions simply calldisplay
. However, some display backends may overrideredisplay
to modify an existing display ofx
(if any). Usingredisplay
is also a hint to the backend thatx
may be redisplayed several times, and the backend may choose to defer the display until (for example) the next interactive prompt.
-
displayable
(mime) → Bool¶ -
displayable
(d::Display, mime) → Bool Returns a boolean value indicating whether the given
mime
type (string) is displayable by any of the displays in the current display stack, or specifically by the displayd
in the second variant.
-
writemime
(stream, mime, x)¶ The
display
functions ultimately callwritemime
in order to write an objectx
as a givenmime
type to a given I/Ostream
(usually a memory buffer), if possible. In order to provide a rich multimedia representation of a user-defined typeT
, it is only necessary to define a newwritemime
method forT
, via:writemime(stream, ::MIME"mime", x::T) = ...
, wheremime
is a MIME-type string and the function body callswrite
(or similar) to write that representation ofx
tostream
. (Note that theMIME""
notation only supports literal strings; to constructMIME
types in a more flexible manner useMIME{symbol("")}
.)For example, if you define a
MyImage
type and know how to write it to a PNG file, you could define a functionwritemime(stream, ::MIME"image/png", x::MyImage) = ...`
to allow your images to be displayed on any PNG-capableDisplay
(such as IJulia). As usual, be sure toimport Base.writemime
in order to add new methods to the built-in Julia functionwritemime
.Technically, the
MIME"mime"
macro defines a singleton type for the givenmime
string, which allows us to exploit Julia’s dispatch mechanisms in determining how to display objects of any given type.
-
mimewritable
(mime, x)¶ Returns a boolean value indicating whether or not the object
x
can be written as the givenmime
type. (By default, this is determined automatically by the existence of the correspondingwritemime
function fortypeof(x)
.)
-
reprmime
(mime, x)¶ Returns a
String
orVector{Uint8}
containing the representation ofx
in the requestedmime
type, as written bywritemime
(throwing aMethodError
if no appropriatewritemime
is available). AString
is returned for MIME types with textual representations (such as"text/html"
or"application/postscript"
), whereas binary data is returned asVector{Uint8}
. (The functionistext(mime)
returns whether or not Julia treats a givenmime
type as text.)As a special case, if
x
is aString
(for textual MIME types) or aVector{Uint8}
(for binary MIME types), thereprmime
function assumes thatx
is already in the requestedmime
format and simply returnsx
.
-
stringmime
(mime, x)¶ Returns a
String
containing the representation ofx
in the requestedmime
type. This is similar toreprmime
except that binary data is base64-encoded as an ASCII string.
As mentioned above, one can also define new display backends. For
example, a module that can display PNG images in a window can register
this capability with Julia, so that calling display(x)
on types
with PNG representations will automatically display the image using
the module’s window.
In order to define a new display backend, one should first create a
subtype D
of the abstract class Display
. Then, for each MIME
type (mime
string) that can be displayed on D
, one should
define a function display(d::D, ::MIME"mime", x) = ...
that
displays x
as that MIME type, usually by calling reprmime(mime,
x)
. A MethodError
should be thrown if x
cannot be displayed
as that MIME type; this is automatic if one calls reprmime
.
Finally, one should define a function display(d::D, x)
that
queries mimewritable(mime, x)
for the mime
types supported by
D
and displays the “best” one; a MethodError
should be thrown
if no supported MIME types are found for x
. Similarly, some
subtypes may wish to override redisplay(d::D, ...)
. (Again, one
should import Base.display
to add new methods to display
.)
The return values of these functions are up to the implementation
(since in some cases it may be useful to return a display “handle” of
some type). The display functions for D
can then be called
directly, but they can also be invoked automatically from
display(x)
simply by pushing a new display onto the display-backend
stack with:
-
pushdisplay
(d::Display)¶ Pushes a new display
d
on top of the global display-backend stack. Callingdisplay(x)
ordisplay(mime, x)
will displayx
on the topmost compatible backend in the stack (i.e., the topmost backend that does not throw aMethodError
).
-
popdisplay
()¶ -
popdisplay
(d::Display) Pop the topmost backend off of the display-backend stack, or the topmost copy of
d
in the second variant.
-
TextDisplay
(stream)¶ Returns a
TextDisplay <: Display
, which can display any object as the text/plain MIME type (only), writing the text representation to the given I/O stream. (The text representation is the same as the way an object is printed in the Julia REPL.)
-
istext
(m::MIME)¶ Determine whether a MIME type is text data.
Memory-mapped I/O¶
-
mmap_array
(type, dims, stream[, offset])¶ Create an
Array
whose values are linked to a file, using memory-mapping. This provides a convenient way of working with data too large to fit in the computer’s memory.The type determines how the bytes of the array are interpreted. Note that the file must be stored in binary format, and no format conversions are possible (this is a limitation of operating systems, not Julia).
dims
is a tuple specifying the size of the array.The file is passed via the stream argument. When you initialize the stream, use
"r"
for a “read-only” array, and"w+"
to create a new array used to write values to disk.Optionally, you can specify an offset (in bytes) if, for example, you want to skip over a header in the file. The default value for the offset is the current stream position.
For example, the following code:
# Create a file for mmapping # (you could alternatively use mmap_array to do this step, too) A = rand(1:20, 5, 30) s = open("/tmp/mmap.bin", "w+") # We'll write the dimensions of the array as the first two Ints in the file write(s, size(A,1)) write(s, size(A,2)) # Now write the data write(s, A) close(s) # Test by reading it back in s = open("/tmp/mmap.bin") # default is read-only m = read(s, Int) n = read(s, Int) A2 = mmap_array(Int, (m,n), s)
creates a
m
-by-n
Matrix{Int}
, linked to the file associated with streams
.A more portable file would need to encode the word size—32 bit or 64 bit—and endianness information in the header. In practice, consider encoding binary data using standard formats like HDF5 (which can be used with memory-mapping).
-
mmap_bitarray
([type, ]dims, stream[, offset])¶ Create a
BitArray
whose values are linked to a file, using memory-mapping; it has the same purpose, works in the same way, and has the same arguments, asmmap_array()
, but the byte representation is different. Thetype
parameter is optional, and must beBool
if given.Example:
B = mmap_bitarray((25,30000), s)
This would create a 25-by-30000
BitArray
, linked to the file associated with streams
.
-
msync
(array)¶ Forces synchronization between the in-memory version of a memory-mapped
Array
orBitArray
and the on-disk version.
-
msync
(ptr, len[, flags]) Forces synchronization of the
mmap()
ped memory region fromptr
toptr+len
. Flags defaults toMS_SYNC
, but can be a combination ofMS_ASYNC
,MS_SYNC
, orMS_INVALIDATE
. See your platform man page for specifics. The flags argument is not valid on Windows.You may not need to call
msync
, because synchronization is performed at intervals automatically by the operating system. However, you can call this directly if, for example, you are concerned about losing the result of a long-running calculation.
-
MS_ASYNC
¶ Enum constant for
msync()
. See your platform man page for details. (not available on Windows).
-
MS_SYNC
¶ Enum constant for
msync()
. See your platform man page for details. (not available on Windows).
-
MS_INVALIDATE
¶ Enum constant for
msync()
. See your platform man page for details. (not available on Windows).
-
mmap
(len, prot, flags, fd, offset)¶ Low-level interface to the
mmap
system call. See the man page.
-
munmap
(pointer, len)¶ Low-level interface for unmapping memory (see the man page). With
mmap_array()
you do not need to call this directly; the memory is unmapped for you when the array goes out of scope.
Standard Numeric Types¶
Bool
Int8
Uint8
Int16
Uint16
Int32
Uint32
Int64
Uint64
Int128
Uint128
Float16
Float32
Float64
Complex64
Complex128
Mathematical Operators¶
-
-
(x)¶ Unary minus operator.
-
+
(x, y...)¶ Addition operator.
x+y+z+...
calls this function with all arguments, i.e.+(x, y, z, ...)
.
-
-
(x, y) Subtraction operator.
-
*
(x, y...) Multiplication operator.
x*y*z*...
calls this function with all arguments, i.e.*(x, y, z, ...)
.
-
/
(x, y)¶ Right division operator: multiplication of
x
by the inverse ofy
on the right. Gives floating-point results for integer arguments.
-
\
(x, y)¶ Left division operator: multiplication of
y
by the inverse ofx
on the left. Gives floating-point results for integer arguments.
-
^
(x, y) Exponentiation operator.
-
.+
(x, y)¶ Element-wise addition operator.
-
.-
(x, y)¶ Element-wise subtraction operator.
-
.*
(x, y)¶ Element-wise multiplication operator.
-
./
(x, y)¶ Element-wise right division operator.
-
.\
(x, y)¶ Element-wise left division operator.
-
.^
(x, y)¶ Element-wise exponentiation operator.
-
div
(a, b)¶ Compute a/b, truncating to an integer.
-
fld
(a, b)¶ Largest integer less than or equal to a/b.
-
mod
(x, m)¶ Modulus after division, returning in the range [0,m).
-
mod2pi
(x)¶ Modulus after division by 2pi, returning in the range [0,2pi).
This function computes a floating point representation of the modulus after division by numerically exact 2pi, and is therefore not exactly the same as mod(x,2pi), which would compute the modulus of x relative to division by the floating-point number 2pi.
-
rem
(x, m)¶ Remainder after division.
-
divrem
(x, y)¶ Returns
(x/y, x%y)
.
-
%
(x, m)¶ Remainder after division. The operator form of
rem
.
-
mod1
(x, m)¶ Modulus after division, returning in the range (0,m]
-
rem1
(x, m)¶ Remainder after division, returning in the range (0,m]
-
//
(num, den)¶ Divide two integers or rational numbers, giving a
Rational
result.
-
rationalize
([Type=Int, ]x; tol=eps(x))¶ Approximate floating point number
x
as a Rational number with components of the given integer type. The result will differ fromx
by no more thantol
.
-
num
(x)¶ Numerator of the rational representation of
x
-
den
(x)¶ Denominator of the rational representation of
x
-
<<
(x, n)¶ Left bit shift operator.
-
>>
(x, n)¶ Right bit shift operator, preserving the sign of
x
.
-
>>>
(x, n)¶ Unsigned right bit shift operator.
-
:
(start, [step, ]stop)¶ Range operator.
a:b
constructs a range froma
tob
with a step size of 1, anda:s:b
is similar but uses a step size ofs
. These syntaxes call the functioncolon
. The colon is also used in indexing to select whole dimensions.
-
colon
(start, [step, ]stop)¶ Called by
:
syntax for constructing ranges.
-
range
(start, [step, ]length)¶ Construct a range by length, given a starting value and optional step (defaults to 1).
-
linrange
(start, end, length)¶ Construct a range by length, given a starting and ending value.
-
==
(x, y)¶ Generic equality operator, giving a single
Bool
result. Falls back to===
. Should be implemented for all types with a notion of equality, based on the abstract value that an instance represents. For example, all numeric types are compared by numeric value, ignoring type. Strings are compared as sequences of characters, ignoring encoding.Follows IEEE semantics for floating-point numbers.
Collections should generally implement
==
by calling==
recursively on all contents.New numeric types should implement this function for two arguments of the new type, and handle comparison to other types via promotion rules where possible.
-
!=
(x, y)¶ Not-equals comparison operator. Always gives the opposite answer as
==
. New types should generally not implement this, and rely on the fallback definition!=(x,y) = !(x==y)
instead.
-
===
(x, y)¶ See the
is()
operator
-
!==
(x, y)¶ Equivalent to
!is(x, y)
-
<
(x, y)¶ Less-than comparison operator. New numeric types should implement this function for two arguments of the new type. Because of the behavior of floating-point NaN values,
<
implements a partial order. Types with a canonical partial order should implement<
, and types with a canonical total order should implementisless
.
-
<=
(x, y)¶ Less-than-or-equals comparison operator.
-
>
(x, y)¶ Greater-than comparison operator. Generally, new types should implement
<
instead of this function, and rely on the fallback definition>(x,y) = y<x
.
-
>=
(x, y)¶ Greater-than-or-equals comparison operator.
-
.==
(x, y)¶ Element-wise equality comparison operator.
-
.!=
(x, y)¶ Element-wise not-equals comparison operator.
-
.<
(x, y)¶ Element-wise less-than comparison operator.
-
.<=
(x, y)¶ Element-wise less-than-or-equals comparison operator.
-
.>
(x, y)¶ Element-wise greater-than comparison operator.
-
.>=
(x, y)¶ Element-wise greater-than-or-equals comparison operator.
-
cmp
(x, y)¶ Return -1, 0, or 1 depending on whether
x
is less than, equal to, or greater thany
, respectively. Uses the total order implemented byisless
. For floating-point numbers, uses<
but throws an error for unordered arguments.
-
~
(x)¶ Bitwise not
-
&
(x, y)¶ Bitwise and
-
|
(x, y)¶ Bitwise or
-
$
(x, y)¶ Bitwise exclusive or
-
!
(x)¶ Boolean not
-
x && y
Short-circuiting boolean and
-
x || y
Short-circuiting boolean or
-
A_ldiv_Bc
(a, b)¶ Matrix operator A \ BH
-
A_ldiv_Bt
(a, b)¶ Matrix operator A \ BT
-
A_mul_B
(...)¶ Matrix operator A B
-
A_mul_Bc
(...)¶ Matrix operator A BH
-
A_mul_Bt
(...)¶ Matrix operator A BT
-
A_rdiv_Bc
(...)¶ Matrix operator A / BH
-
A_rdiv_Bt
(a, b)¶ Matrix operator A / BT
-
Ac_ldiv_B
(...)¶ Matrix operator AH \ B
-
Ac_ldiv_Bc
(...)¶ Matrix operator AH \ BH
-
Ac_mul_B
(...)¶ Matrix operator AH B
-
Ac_mul_Bc
(...)¶ Matrix operator AH BH
-
Ac_rdiv_B
(a, b)¶ Matrix operator AH / B
-
Ac_rdiv_Bc
(a, b)¶ Matrix operator AH / BH
-
At_ldiv_B
(...)¶ Matrix operator AT \ B
-
At_ldiv_Bt
(...)¶ Matrix operator AT \ BT
-
At_mul_B
(...)¶ Matrix operator AT B
-
At_mul_Bt
(...)¶ Matrix operator AT BT
-
At_rdiv_B
(a, b)¶ Matrix operator AT / B
-
At_rdiv_Bt
(a, b)¶ Matrix operator AT / BT
Mathematical Functions¶
-
isapprox
(x::Number, y::Number; rtol::Real=cbrt(maxeps), atol::Real=sqrt(maxeps))¶ Inexact equality comparison - behaves slightly different depending on types of input args:
- For
FloatingPoint
numbers,isapprox
returnstrue
ifabs(x-y) <= atol + rtol*max(abs(x), abs(y))
. - For
Integer
andRational
numbers,isapprox
returnstrue
ifabs(x-y) <= atol
. The rtol argument is ignored. If one ofx
andy
isFloatingPoint
, the other is promoted, and the method above is called instead. - For
Complex
numbers, the distance in the complex plane is compared, using the same criterion as above.
For default tolerance arguments,
maxeps = max(eps(abs(x)), eps(abs(y)))
.- For
-
sin
(x)¶ Compute sine of
x
, wherex
is in radians
-
cos
(x)¶ Compute cosine of
x
, wherex
is in radians
-
tan
(x)¶ Compute tangent of
x
, wherex
is in radians
-
sind
(x)¶ Compute sine of
x
, wherex
is in degrees
-
cosd
(x)¶ Compute cosine of
x
, wherex
is in degrees
-
tand
(x)¶ Compute tangent of
x
, wherex
is in degrees
-
sinpi
(x)¶ Compute \(\sin(\pi x)\) more accurately than
sin(pi*x)
, especially for largex
.
-
cospi
(x)¶ Compute \(\cos(\pi x)\) more accurately than
cos(pi*x)
, especially for largex
.
-
sinh
(x)¶ Compute hyperbolic sine of
x
-
cosh
(x)¶ Compute hyperbolic cosine of
x
-
tanh
(x)¶ Compute hyperbolic tangent of
x
-
asin
(x)¶ Compute the inverse sine of
x
, where the output is in radians
-
acos
(x)¶ Compute the inverse cosine of
x
, where the output is in radians
-
atan
(x)¶ Compute the inverse tangent of
x
, where the output is in radians
-
atan2
(y, x)¶ Compute the inverse tangent of
y/x
, using the signs of bothx
andy
to determine the quadrant of the return value.
-
asind
(x)¶ Compute the inverse sine of
x
, where the output is in degrees
-
acosd
(x)¶ Compute the inverse cosine of
x
, where the output is in degrees
-
atand
(x)¶ Compute the inverse tangent of
x
, where the output is in degrees
-
sec
(x)¶ Compute the secant of
x
, wherex
is in radians
-
csc
(x)¶ Compute the cosecant of
x
, wherex
is in radians
-
cot
(x)¶ Compute the cotangent of
x
, wherex
is in radians
-
secd
(x)¶ Compute the secant of
x
, wherex
is in degrees
-
cscd
(x)¶ Compute the cosecant of
x
, wherex
is in degrees
-
cotd
(x)¶ Compute the cotangent of
x
, wherex
is in degrees
-
asec
(x)¶ Compute the inverse secant of
x
, where the output is in radians
-
acsc
(x)¶ Compute the inverse cosecant of
x
, where the output is in radians
-
acot
(x)¶ Compute the inverse cotangent of
x
, where the output is in radians
-
asecd
(x)¶ Compute the inverse secant of
x
, where the output is in degrees
-
acscd
(x)¶ Compute the inverse cosecant of
x
, where the output is in degrees
-
acotd
(x)¶ Compute the inverse cotangent of
x
, where the output is in degrees
-
sech
(x)¶ Compute the hyperbolic secant of
x
-
csch
(x)¶ Compute the hyperbolic cosecant of
x
-
coth
(x)¶ Compute the hyperbolic cotangent of
x
-
asinh
(x)¶ Compute the inverse hyperbolic sine of
x
-
acosh
(x)¶ Compute the inverse hyperbolic cosine of
x
-
atanh
(x)¶ Compute the inverse hyperbolic tangent of
x
-
asech
(x)¶ Compute the inverse hyperbolic secant of
x
-
acsch
(x)¶ Compute the inverse hyperbolic cosecant of
x
-
acoth
(x)¶ Compute the inverse hyperbolic cotangent of
x
-
sinc
(x)¶ Compute \(\sin(\pi x) / (\pi x)\) if \(x \neq 0\), and \(1\) if \(x = 0\).
-
cosc
(x)¶ Compute \(\cos(\pi x) / x - \sin(\pi x) / (\pi x^2)\) if \(x \neq 0\), and \(0\) if \(x = 0\). This is the derivative of
sinc(x)
.
-
deg2rad
(x)¶ Convert
x
from degrees to radians
-
rad2deg
(x)¶ Convert
x
from radians to degrees
-
hypot
(x, y)¶ Compute the \(\sqrt{x^2+y^2}\) avoiding overflow and underflow
-
log
(x)¶ Compute the natural logarithm of
x
. ThrowsDomainError
for negativeReal
arguments. Use complex negative arguments instead.
-
log
(b, x) Compute the base
b
logarithm ofx
. ThrowsDomainError
for negativeReal
arguments.
-
log2
(x)¶ Compute the logarithm of
x
to base 2. ThrowsDomainError
for negativeReal
arguments.
-
log10
(x)¶ Compute the logarithm of
x
to base 10. ThrowsDomainError
for negativeReal
arguments.
-
log1p
(x)¶ Accurate natural logarithm of
1+x
. ThrowsDomainError
forReal
arguments less than -1.
-
frexp
(val)¶ Return
(x,exp)
such thatx
has a magnitude in the interval[1/2, 1)
or 0, and val = \(x \times 2^{exp}\).
-
exp
(x)¶ Compute \(e^x\)
-
exp2
(x)¶ Compute \(2^x\)
-
exp10
(x)¶ Compute \(10^x\)
-
ldexp
(x, n)¶ Compute \(x \times 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 asx
tox
.round(x, digits)
rounds to the specified number of digits after the decimal place, or before if negative, e.g.,round(pi,2)
is3.14
.round(x, digits, base)
rounds using a different base, defaulting to 10, e.g.,round(pi, 1, 8)
is3.125
.
-
ceil
(x[, digits[, base]])¶ Returns the nearest integral value of the same type as
x
not less thanx
.digits
andbase
work as above.
-
floor
(x[, digits[, base]])¶ Returns the nearest integral value of the same type as
x
not greater thanx
.digits
andbase
work as above.
-
trunc
(x[, digits[, base]])¶ Returns the nearest integral value of the same type as
x
not greater in magnitude thanx
.digits
andbase
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 aredigits
significant digits, under a basebase
representation, default 10. E.g.,signif(123.456, 2)
is120.0
, andsignif(357.913, 4, 2)
is352.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
. Ifx < lo
, returnlo
. Ifx > hi
, returnhi
. Arguments are promoted to a common type. Operates elementwise overx
if it is an array.
-
abs
(x)¶ Absolute value of
x
-
abs2
(x)¶ Squared absolute value of
x
-
copysign
(x, y)¶ Return
x
such that it has the same sign asy
-
sign
(x)¶ Return
+1
ifx
is positive,0
ifx == 0
, and-1
ifx
is negative.
-
signbit
(x)¶ Returns
1
if the value of the sign ofx
is negative, otherwise0
.
-
flipsign
(x, y)¶ Return
x
with its sign flipped ify
is negative. For exampleabs(x) = flipsign(x,x)
.
-
sqrt
(x)¶ Return \(\sqrt{x}\). Throws
DomainError
for negativeReal
arguments. Use complex negative arguments instead. The prefix operator√
is equivalent tosqrt
.
-
isqrt
(n)¶ Integer square root: the largest integer
m
such thatm*m <= n
.
-
cbrt
(x)¶ Return \(x^{1/3}\). The prefix operator
∛
is equivalent tocbrt
.
-
erf
(x)¶ Compute the error function of
x
, defined by \(\frac{2}{\sqrt{\pi}} \int_0^x e^{-t^2} dt\) for arbitrary complexx
.
-
erfc
(x)¶ Compute the complementary error function of
x
, defined by \(1 - \operatorname{erf}(x)\).
-
erfcx
(x)¶ Compute the scaled complementary error function of
x
, defined by \(e^{x^2} \operatorname{erfc}(x)\). Note also that \(\operatorname{erfcx}(-ix)\) computes the Faddeeva function \(w(x)\).
-
erfi
(x)¶ Compute the imaginary error function of
x
, defined by \(-i \operatorname{erf}(ix)\).
-
dawson
(x)¶ Compute the Dawson function (scaled imaginary error function) of
x
, defined by \(\frac{\sqrt{\pi}}{2} e^{-x^2} \operatorname{erfi}(x)\).
-
erfinv
(x)¶ Compute the inverse error function of a real
x
, defined by \(\operatorname{erf}(\operatorname{erfinv}(x)) = x\).
-
erfcinv
(x)¶ Compute the inverse error complementary function of a real
x
, defined by \(\operatorname{erfc}(\operatorname{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)\).
-
binomial
(n, k)¶ Number of ways to choose
k
out ofn
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 asn
. 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
andy
and their Bézout coefficients, i.e. the integer coefficientsu
andv
that satisfy \(ux+vy = d = gcd(x,y)\).julia> gcdx(12, 42) (6,-3,1)
julia> gcdx(240, 46) (2,-9,47)
注解
Bézout coefficients are not uniquely defined.
gcdx
returns the minimal Bézout coefficients that are computed by the extended Euclid algorithm. (Ref: D. Knuth, TAoCP, 2/e, p. 325, Algorithm X.) These coefficientsu
andv
are minimal in the sense that \(|u| < |\frac y d\) and \(|v| < |\frac x d\). Furthermore, the signs ofu
andv
are chosen so thatd
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 forn==0
, and returns-nextpow2(-n)
for negative arguments.
-
prevpow2
(n)¶ The largest power of two not greater than
n
. Returns 0 forn==0
, and returns-prevpow2(-n)
for negative arguments.
-
nextpow
(a, x)¶ The smallest
a^n
not less thanx
, wheren
is a non-negative integer.a
must be greater than 1, andx
must be greater than 0.
-
prevpow
(a, x)¶ The largest
a^n
not greater thanx
, wheren
is a non-negative integer.a
must be greater than 1, andx
must not be less than 1.
-
nextprod
([k_1, k_2, ..., ]n)¶ Next integer not less than
n
that can be written as \(\prod k_i^{p_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 \(\prod k_i^{p_i}\) for integers \(p_1\), \(p_2\), etc.
-
invmod
(x, m)¶ Take the inverse of
x
modulom
:y
such that \(xy = 1 \pmod m\)
-
powermod
(x, p, m)¶ Compute \(x^p \pmod 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 ofgamma(x)
)
-
invdigamma
(x)¶ Compute the inverse digamma function of
x
.
-
trigamma
(x)¶ Compute the trigamma function of
x
(the logarithmic second derivative ofgamma(x)
)
-
polygamma
(m, x)¶ Compute the polygamma function of order
m
of argumentx
(the(m+1)th
derivative of the logarithm ofgamma(x)
)
-
airy
(k, x)¶ kth derivative of the Airy function \(\operatorname{Ai}(x)\).
-
airyai
(x)¶ Airy function \(\operatorname{Ai}(x)\).
-
airyprime
(x)¶ Airy function derivative \(\operatorname{Ai}'(x)\).
-
airyaiprime
(x)¶ Airy function derivative \(\operatorname{Ai}'(x)\).
-
airybi
(x)¶ Airy function \(\operatorname{Bi}(x)\).
-
airybiprime
(x)¶ Airy function derivative \(\operatorname{Bi}'(x)\).
-
airyx
(k, x)¶ scaled kth derivative of the Airy function, return \(\operatorname{Ai}(x) e^{\frac{2}{3} x \sqrt{x}}\) for
k == 0 || k == 1
, and \(\operatorname{Ai}(x) e^{- \left| \operatorname{Re} \left( \frac{2}{3} x \sqrt{x} \right) \right|}\) fork == 2 || k == 3
.
-
besselj0
(x)¶ Bessel function of the first kind of order 0, \(J_0(x)\).
-
besselj1
(x)¶ Bessel function of the first kind of order 1, \(J_1(x)\).
-
besselj
(nu, x)¶ Bessel function of the first kind of order
nu
, \(J_\nu(x)\).
-
besseljx
(nu, x)¶ Scaled Bessel function of the first kind of order
nu
, \(J_\nu(x) e^{- | \operatorname{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_\nu(x)\).
-
besselyx
(nu, x)¶ Scaled Bessel function of the second kind of order
nu
, \(Y_\nu(x) e^{- | \operatorname{Im}(x) |}\).
-
hankelh1
(nu, x)¶ Bessel function of the third kind of order
nu
, \(H^{(1)}_\nu(x)\).
-
hankelh1x
(nu, x)¶ Scaled Bessel function of the third kind of order
nu
, \(H^{(1)}_\nu(x) e^{-x i}\).
-
hankelh2
(nu, x)¶ Bessel function of the third kind of order
nu
, \(H^{(2)}_\nu(x)\).
-
hankelh2x
(nu, x)¶ Scaled Bessel function of the third kind of order
nu
, \(H^{(2)}_\nu(x) e^{x i}\).
-
besselh
(nu, k, x)¶ Bessel function of the third kind of order
nu
(Hankel function).k
is either 1 or 2, selectinghankelh1
orhankelh2
, respectively.
-
besseli
(nu, x)¶ Modified Bessel function of the first kind of order
nu
, \(I_\nu(x)\).
-
besselix
(nu, x)¶ Scaled modified Bessel function of the first kind of order
nu
, \(I_\nu(x) e^{- | \operatorname{Re}(x) |}\).
-
besselk
(nu, x)¶ Modified Bessel function of the second kind of order
nu
, \(K_\nu(x)\).
-
besselkx
(nu, x)¶ Scaled modified Bessel function of the second kind of order
nu
, \(K_\nu(x) e^x\).
-
beta
(x, y)¶ Euler integral of the first kind \(\operatorname{B}(x,y) = \Gamma(x)\Gamma(y)/\Gamma(x+y)\).
-
lbeta
(x, y)¶ Natural logarithm of the absolute value of the beta function \(\log(|\operatorname{B}(x,y)|)\).
-
eta
(x)¶ Dirichlet eta function \(\eta(s) = \sum^\infty_{n=1}(-)^{n-1}/n^{s}\).
-
zeta
(s)¶ Riemann zeta function \(\zeta(s)\).
-
zeta
(s, z) Hurwitz zeta function \(\zeta(s, z)\). (This is equivalent to the Riemann zeta function \(\zeta(s)\) for the case of
z=1
.)
-
ndigits
(n, b)¶ Compute the number of digits in number
n
written in baseb
.
-
widemul
(x, y)¶ Multiply
x
andy
, giving the result as a larger type.
-
@evalpoly
(z, c...)¶ Evaluate the polynomial \(\sum_k c[k] z^{k-1}\) for the coefficients
c[1]
,c[2]
, ...; that is, the coefficients are given in ascending order by power ofz
. This macro expands to efficient inline code that uses either Horner’s method or, for complexz
, a more efficient Goertzel-like algorithm.
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 specified 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 specified size. More significant digits are at higher indexes, such thatn == 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 significant digits are at higher indexes. If the array length is insufficient, the least significant digits are filled up to the array length. If the array length is excessive, the excess portion is filled 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 specified type (default
Int
).
-
parsefloat
([type, ]str)¶ Parse a string as a decimal floating point number, yielding a number of the specified type.
-
big
(x)¶ Convert a number to a maximum precision representation (typically
BigInt
orBigFloat
). SeeBigFloat
for information about some pitfalls with floating-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.
-
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 inout[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 inout[1]
.
-
float
(x)¶ Convert a number, array, or string to a
FloatingPoint
data type. For numeric data, the smallest suitableFloatingPoint
type is used. Converts strings toFloat64
.This function is not recommended for arrays. It is better to use a more specific function such as
float32
orfloat64
.
-
significand
(x)¶ Extract the significand(s) (a.k.a. mantissa), in binary representation, of a floating-point number or array.
julia> significand(15.2)/15.2 0.125 julia> significand(15.2)*8 15.2
-
exponent
(x) → Int¶ Get the exponent of a normalized floating-point number.
-
complex64
(r[, i])¶ Convert to
r + i*im
represented as aComplex64
data type.i
defaults to zero.
-
complex128
(r[, i])¶ Convert to
r + i*im
represented as aComplex128
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 floating point number
-
hex2num
(str)¶ Convert a hexadecimal string to the floating 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 ASCIIString.
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
¶ Catalan’s constant
-
Inf
¶ Positive infinity of type Float64
-
Inf32
¶ Positive infinity of type Float32
-
Inf16
¶ Positive infinity of type Float16
-
NaN
¶ A not-a-number value of type Float64
-
NaN32
¶ A not-a-number value of type Float32
-
NaN16
¶ A not-a-number value of type Float16
-
issubnormal
(f) → Bool¶ Test whether a floating point number is subnormal
-
isfinite
(f) → Bool¶ Test whether a number is finite
-
isinf
(f) → Bool¶ Test whether a number is infinite
-
isnan
(f) → Bool¶ Test whether a floating point number is not a number (NaN)
-
inf
(f)¶ Returns positive infinity of the floating point type
f
or of the same floating point type asf
-
nan
(f)¶ Returns NaN (not-a-number) of the floating point type
f
or of the same floating point type asf
-
nextfloat
(f)¶ Get the next floating point number in lexicographic order
-
prevfloat
(f) → FloatingPoint¶ Get the previous floating point number in lexicographic order
-
isinteger
(x) → Bool¶ Test whether
x
or all its elements are numerically equal to some integer
-
isreal
(x) → Bool¶ Test whether
x
or all its elements are numerically equal to some real number
-
BigInt
(x)¶ Create an arbitrary precision integer.
x
may be anInt
(or anything that can be converted to anInt
) or aString
. The usual mathematical operators are defined for this type, and results are promoted to aBigInt
.
-
BigFloat
(x)¶ Create an arbitrary precision floating point number.
x
may be anInteger
, aFloat64
, aString
or aBigInt
. The usual mathematical operators are defined for this type, and results are promoted to aBigFloat
. Note that because floating-point numbers are not exactly-representable in decimal notation,BigFloat(2.1)
may not yield what you expect. You may prefer to initialize constants using strings, e.g.,BigFloat("2.1")
.
-
get_rounding
(T)¶ Get the current floating point rounding mode for type
T
. Valid modes areRoundNearest
,RoundToZero
,RoundUp
,RoundDown
, andRoundFromZero
(BigFloat
only).
-
set_rounding
(T, mode)¶ Set the rounding mode of floating point type
T
. Note that this may affect other types, for instance changing the rounding mode ofFloat64
will change the rounding mode ofFloat32
. Seeget_rounding
for available modes
-
with_rounding
(f::Function, T, mode)¶ Change the rounding mode of floating point type
T
for the duration off
. It is logically equivalent to:old = get_rounding(T) set_rounding(T, mode) f() set_rounding(T, old)
See
get_rounding
for available rounding modes.
Integers¶
-
count_ones
(x::Integer) → Integer¶ Number of ones in the binary representation of
x
.julia> count_ones(7) 3
-
count_zeros
(x::Integer) → Integer¶ Number of zeros in the binary representation of
x
.julia> count_zeros(int32(2 ^ 16 - 1)) 16
-
leading_zeros
(x::Integer) → Integer¶ Number of zeros leading the binary representation of
x
.julia> leading_zeros(int32(1)) 31
-
leading_ones
(x::Integer) → Integer¶ Number of ones leading the binary representation of
x
.julia> leading_ones(int32(2 ^ 32 - 2)) 31
-
trailing_zeros
(x::Integer) → Integer¶ Number of zeros trailing the binary representation of
x
.julia> trailing_zeros(2) 1
-
trailing_ones
(x::Integer) → Integer¶ Number of ones trailing the binary representation of
x
.julia> trailing_ones(3) 2
-
isprime
(x::Integer) → Bool¶ Returns
true
ifx
is prime, andfalse
otherwise.julia> isprime(3) true
-
primes
(n)¶ Returns a collection of the prime numbers <=
n
.
-
isodd
(x::Integer) → Bool¶ Returns
true
ifx
is odd (that is, not divisible by 2), andfalse
otherwise.julia> isodd(9) true julia> isodd(10) false
-
iseven
(x::Integer) → Bool¶ Returns
true
isx
is even (that is, divisible by 2), andfalse
otherwise.julia> iseven(9) false julia> iseven(10) true
BigFloats¶
The BigFloat type implements arbitrary-precision floating-point aritmetic using the GNU MPFR library.
-
precision
(num::FloatingPoint)¶ Get the precision of a floating point number, as defined by the effective number of bits in the mantissa.
-
get_bigfloat_precision
()¶ Get the precision (in bits) currently used for BigFloat arithmetic.
-
set_bigfloat_precision
(x::Int64)¶ Set the precision (in bits) to be used to BigFloat arithmetic.
-
with_bigfloat_precision
(f::Function, precision::Integer)¶ Change the BigFloat arithmetic precision (in bits) for the duration of
f
. It is logically equivalent to:old = get_bigfloat_precision() set_bigfloat_precision(precision) f() set_bigfloat_precision(old)
Random Numbers¶
Random number generation in Julia uses the Mersenne Twister library. Julia has a global RNG, which is used by default. Multiple RNGs can be plugged in using the AbstractRNG
object, which can then be used to have multiple streams of random numbers. Currently, only MersenneTwister
is supported.
-
srand
([rng, ]seed)¶ Seed the RNG with a
seed
, which may be an unsigned integer or a vector of unsigned integers.seed
can even be a filename, in which case the seed is read from a file. If the argumentrng
is not provided, the default global RNG is seeded.
-
MersenneTwister
([seed])¶ Create a
MersenneTwister
RNG object. Different RNG objects can have their own seeds, which may be useful for generating different streams of random numbers.
-
rand
() → Float64¶ Generate a
Float64
random number uniformly in [0,1)
-
rand!
([rng, ]A)¶ Populate the array A with random number generated from the specified RNG.
-
rand
(rng::AbstractRNG[, dims...]) Generate a random
Float64
number or array of the size specified by dims, using the specified RNG object. Currently,MersenneTwister
is the only available Random Number Generator (RNG), which may be seeded using srand.
-
rand
(dims or [dims...]) Generate a random
Float64
array of the size specified by dims
-
rand
(Int32|Uint32|Int64|Uint64|Int128|Uint128[, dims...]) Generate a random integer of the given type. Optionally, generate an array of random integers of the given type by specifying dims.
-
rand
(r[, dims...]) Generate a random integer from the inclusive interval specified by
Range1 r
(for example,1:n
). Optionally, generate a random integer array.
-
randbool
([dims...])¶ Generate a random boolean value. Optionally, generate an array of random boolean values.
-
randbool!
(A)¶ Fill an array with random boolean values. A may be an
Array
or aBitArray
.
-
randn
([rng], dims or [dims...])¶ Generate a normally-distributed random number with mean 0 and standard deviation 1. Optionally generate an array of normally-distributed random numbers.
-
randn!
([rng, ]A::Array{Float64, N})¶ Fill the array A with normally-distributed (mean 0, standard deviation 1) random numbers. Also see the rand function.
Arrays¶
Basic functions¶
-
ndims
(A) → Integer¶ Returns the number of dimensions of A
-
size
(A)¶ Returns a tuple containing the dimensions of A
-
iseltype
(A, T)¶ Tests whether A or its elements are of type T
-
length
(A) → Integer Returns the number of elements in A
-
countnz
(A)¶ Counts the number of nonzero values in array A (dense or sparse). Note that this is not a constant-time operation. For sparse matrices, one should usually use
nnz
, which returns the number of stored values.
-
conj!
(A)¶ Convert an array to its complex conjugate in-place
-
stride
(A, k)¶ Returns the distance in memory (in number of elements) between adjacent elements in dimension k
-
strides
(A)¶ Returns a tuple of the memory strides in each dimension
-
ind2sub
(dims, index) → subscripts¶ Returns a tuple of subscripts into an array with dimensions
dims
, corresponding to the linear indexindex
Example
i, j, ... = ind2sub(size(A), indmax(A))
provides the indices of the maximum element
-
sub2ind
(dims, i, j, k...) → index¶ The inverse of
ind2sub
, returns the linear index corresponding to the provided subscripts
Constructors¶
-
Array
(type, dims)¶ Construct an uninitialized dense array.
dims
may be a tuple or a series of integer arguments.
-
getindex
(type[, elements...]) Construct a 1-d array of the specified type. This is usually called with the syntax
Type[]
. Element values can be specified usingType[a,b,c,...]
.
-
cell
(dims)¶ Construct an uninitialized cell array (heterogeneous array).
dims
can be either a tuple or a series of integer arguments.
-
zeros
(type, dims)¶ Create an array of all zeros of specified type
-
ones
(type, dims)¶ Create an array of all ones of specified type
-
trues
(dims)¶ Create a
BitArray
with all values set to true
-
falses
(dims)¶ Create a
BitArray
with all values set to false
-
fill
(v, dims)¶ Create an array filled with
v
-
fill!
(A, x)¶ Fill array
A
with valuex
-
reshape
(A, dims)¶ Create an array with the same data as the given array, but with different dimensions. An implementation for a particular type of array may choose whether the data is copied or shared.
-
similar
(array, element_type, dims)¶ Create an uninitialized array of the same type as the given array, but with the specified element type and dimensions. The second and third arguments are both optional. The
dims
argument may be a tuple or a series of integer arguments.
-
reinterpret
(type, A)¶ Change the type-interpretation of a block of memory. For example,
reinterpret(Float32, uint32(7))
interprets the 4 bytes corresponding touint32(7)
as aFloat32
. For arrays, this constructs an array with the same binary data as the given array, but with the specified element type.
-
eye
(n)¶ n-by-n identity matrix
-
eye
(m, n) m-by-n identity matrix
-
eye
(A) Constructs an identity matrix of the same dimensions and type as
A
.
-
linspace
(start, stop, n)¶ Construct a vector of
n
linearly-spaced elements fromstart
tostop
. See also:linrange()
that constructs a range object.
-
logspace
(start, stop, n)¶ Construct a vector of
n
logarithmically-spaced numbers from10^start
to10^stop
.
Mathematical operators and functions¶
All mathematical operations and functions are supported for arrays
-
broadcast
(f, As...)¶ Broadcasts the arrays
As
to a common size by expanding singleton dimensions, and returns an array of the resultsf(as...)
for each position.
-
broadcast!
(f, dest, As...)¶ Like
broadcast
, but store the result ofbroadcast(f, As...)
in thedest
array. Note thatdest
is only used to store the result, and does not supply arguments tof
unless it is also listed in theAs
, as inbroadcast!(f, A, A, B)
to performA[:] = broadcast(f, A, B)
.
-
bitbroadcast
(f, As...)¶ Like
broadcast
, but allocates aBitArray
to store the result, rather then anArray
.
-
broadcast_function
(f)¶ Returns a function
broadcast_f
such thatbroadcast_function(f)(As...) === broadcast(f, As...)
. Most useful in the formconst broadcast_f = broadcast_function(f)
.
-
broadcast!_function
(f)¶ Like
broadcast_function
, but forbroadcast!
.
Indexing, Assignment, and Concatenation¶
-
getindex
(A, inds...) Returns a subset of array
A
as specified byinds
, where eachind
may be anInt
, aRange
, or aVector
.
-
sub
(A, inds...)¶ Returns a SubArray, which stores the input
A
andinds
rather than computing the result immediately. Callinggetindex
on a SubArray computes the indices on the fly.
-
parent
(A)¶ Returns the “parent array” of an array view type (e.g., SubArray), or the array itself if it is not a view
-
parentindexes
(A)¶ From an array view
A
, returns the corresponding indexes in the parent
-
slicedim
(A, d, i)¶ Return all the data of
A
where the index for dimensiond
equalsi
. Equivalent toA[:,:,...,i,:,:,...]
wherei
is in positiond
.
-
slice
(A, inds...)¶ Create a view of the given indexes of array
A
, dropping dimensions indexed with scalars.
-
setindex!
(A, X, inds...) Store values from array
X
within some subset ofA
as specified byinds
.
-
broadcast_getindex
(A, inds...)¶ Broadcasts the
inds
arrays to a common size likebroadcast
, and returns an array of the resultsA[ks...]
, whereks
goes over the positions in the broadcast.
-
broadcast_setindex!
(A, X, inds...)¶ Broadcasts the
X
andinds
arrays to a common size and stores the value from each position inX
at the indices given by the same positions ininds
.
-
cat
(dim, A...)¶ Concatenate the input arrays along the specified dimension
-
vcat
(A...)¶ Concatenate along dimension 1
-
hcat
(A...)¶ Concatenate along dimension 2
-
hvcat
(rows::(Int...), values...)¶ Horizontal and vertical concatenation in one call. This function is called for block matrix syntax. The first argument specifies the number of arguments to concatenate in each block row. For example,
[a b;c d e]
callshvcat((2,3),a,b,c,d,e)
.If the first argument is a single integer
n
, then all block rows are assumed to haven
block columns.
-
flipdim
(A, d)¶ Reverse
A
in dimensiond
.
-
flipud
(A)¶ Equivalent to
flipdim(A,1)
.
-
fliplr
(A)¶ Equivalent to
flipdim(A,2)
.
-
circshift
(A, shifts)¶ Circularly shift the data in an array. The second argument is a vector giving the amount to shift in each dimension.
-
find
(A)¶ Return a vector of the linear indexes of the non-zeros in
A
(determined byA[i]!=0
). A common use of this is to convert a boolean array to an array of indexes of thetrue
elements.
-
find
(f, A) Return a vector of the linear indexes of
A
wheref
returns true.
-
findn
(A)¶ Return a vector of indexes for each dimension giving the locations of the non-zeros in
A
(determined byA[i]!=0
).
-
findnz
(A)¶ Return a tuple
(I, J, V)
whereI
andJ
are the row and column indexes of the non-zero values in matrixA
, andV
is a vector of the non-zero values.
-
findfirst
(A)¶ Return the index of the first non-zero value in
A
(determined byA[i]!=0
).
-
findfirst
(A, v) Return the index of the first element equal to
v
inA
.
-
findfirst
(predicate, A) Return the index of the first element of
A
for whichpredicate
returns true.
-
findnext
(A, i)¶ Find the next index >=
i
of a non-zero element ofA
, or0
if not found.
-
findnext
(predicate, A, i) Find the next index >=
i
of an element ofA
for whichpredicate
returns true, or0
if not found.
-
findnext
(A, v, i) Find the next index >=
i
of an element ofA
equal tov
(using==
), or0
if not found.
-
permutedims
(A, perm)¶ Permute the dimensions of array
A
.perm
is a vector specifying a permutation of lengthndims(A)
. This is a generalization of transpose for multi-dimensional arrays. Transpose is equivalent topermutedims(A,[2,1])
.
-
ipermutedims
(A, perm)¶ Like
permutedims()
, except the inverse of the given permutation is applied.
-
squeeze
(A, dims)¶ Remove the dimensions specified by
dims
from arrayA
-
vec
(Array) → Vector¶ Vectorize an array using column-major convention.
-
promote_shape
(s1, s2)¶ Check two array shapes for compatibility, allowing trailing singleton dimensions, and return whichever shape has more dimensions.
-
checkbounds
(array, indexes...)¶ Throw an error if the specified indexes are not in bounds for the given array.
-
randsubseq
(A, p) → Vector¶ Return a vector consisting of a random subsequence of the given array
A
, where each element ofA
is included (in order) with independent probabilityp
. (Complexity is linear inp*length(A)
, so this function is efficient even ifp
is small andA
is large.) Technically, this process is known as “Bernoulli sampling” ofA
.
-
randsubseq!
(S, A, p)¶ Like
randsubseq
, but the results are stored inS
(which is resized as needed).
Array functions¶
-
cumprod
(A[, dim])¶ Cumulative product along a dimension.
-
cumprod!
(B, A[, dim])¶ Cumulative product of
A
along a dimension, storing the result inB
.
-
cumsum
(A[, dim])¶ Cumulative sum along a dimension.
-
cumsum!
(B, A[, dim])¶ Cumulative sum of
A
along a dimension, storing the result inB
.
-
cumsum_kbn
(A[, dim])¶ Cumulative sum along a dimension, using the Kahan-Babuska-Neumaier compensated summation algorithm for additional accuracy.
-
cummin
(A[, dim])¶ Cumulative minimum along a dimension.
-
cummax
(A[, dim])¶ Cumulative maximum along a dimension.
-
diff
(A[, dim])¶ Finite difference operator of matrix or vector.
-
gradient
(F[, h])¶ Compute differences along vector
F
, usingh
as the spacing between points. The default spacing is one.
-
rot180
(A)¶ Rotate matrix
A
180 degrees.
-
rotl90
(A)¶ Rotate matrix
A
left 90 degrees.
-
rotr90
(A)¶ Rotate matrix
A
right 90 degrees.
-
reducedim
(f, A, dims, initial)¶ Reduce 2-argument function
f
along dimensions ofA
.dims
is a vector specifying the dimensions to reduce, andinitial
is the initial value to use in the reductions.The associativity of the reduction is implementation-dependent; if you need a particular associativity, e.g. left-to-right, you should write your own loop. See documentation for
reduce
.
-
mapslices
(f, A, dims)¶ Transform the given dimensions of array
A
using functionf
.f
is called on each slice ofA
of the formA[...,:,...,:,...]
.dims
is an integer vector specifying where the colons go in this expression. The results are concatenated along the remaining dimensions. For example, ifdims
is[1,2]
and A is 4-dimensional,f
is called onA[:,:,i,j]
for alli
andj
.
-
sum_kbn
(A)¶ Returns the sum of all array elements, using the Kahan-Babuska-Neumaier compensated summation algorithm for additional accuracy.
-
cartesianmap
(f, dims)¶ Given a
dims
tuple of integers(m, n, ...)
, callf
on all combinations of integers in the ranges1:m
,1:n
, etc.julia> cartesianmap(println, (2,2)) 11 21 12 22
BitArrays¶
-
bitpack
(A::AbstractArray{T, N}) → BitArray¶ Converts a numeric array to a packed boolean array
-
bitunpack
(B::BitArray{N}) → Array{Bool,N}¶ Converts a packed boolean array to an array of booleans
-
flipbits!
(B::BitArray{N}) → BitArray{N}¶ Performs a bitwise not operation on B. See ~ operator.
-
rol
(B::BitArray{1}, i::Integer) → BitArray{1}¶ Left rotation operator.
-
ror
(B::BitArray{1}, i::Integer) → BitArray{1}¶ Right rotation operator.
Combinatorics¶
-
nthperm
(v, k)¶ Compute the kth lexicographic permutation of a vector.
-
nthperm
(p) Return the
k
that generated permutationp
. Note thatnthperm(nthperm([1:n], k)) == k
for1 <= k <= factorial(n)
.
-
nthperm!
(v, k)¶ In-place version of
nthperm()
.
-
randperm
(n)¶ Construct a random permutation of the given length.
-
invperm
(v)¶ Return the inverse permutation of v.
-
isperm
(v) → Bool¶ Returns true if v is a valid permutation.
-
permute!
(v, p)¶ Permute vector
v
in-place, according to permutationp
. No checking is done to verify thatp
is a permutation.To return a new permutation, use
v[p]
. Note that this is generally faster thanpermute!(v,p)
for large vectors.
-
ipermute!
(v, p)¶ Like permute!, but the inverse of the given permutation is applied.
-
randcycle
(n)¶ Construct a random cyclic permutation of the given length.
-
shuffle
(v)¶ Return a randomly permuted copy of
v
.
-
shuffle!
(v)¶ In-place version of
shuffle()
.
-
reverse
(v[, start=1[, stop=length(v)]])¶ Return a copy of
v
reversed from start to stop.
-
reverse!
(v[, start=1[, stop=length(v)]]) → v¶ In-place version of
reverse()
.
-
combinations
(arr, n)¶ Generate all combinations of
n
elements from an indexable object. Because the number of combinations can be very large, this function returns an iterator object. Usecollect(combinations(a,n))
to get an array of all combinations.
-
permutations
(arr)¶ Generate all permutations of an indexable object. Because the number of permutations can be very large, this function returns an iterator object. Use
collect(permutations(a,n))
to get an array of all permutations.
-
partitions
(n)¶ Generate all integer arrays that sum to
n
. Because the number of partitions can be very large, this function returns an iterator object. Usecollect(partitions(n))
to get an array of all partitions. The number of partitions to generete can be efficiently computed usinglength(partitions(n))
.
-
partitions
(n, m) Generate all arrays of
m
integers that sum ton
. Because the number of partitions can be very large, this function returns an iterator object. Usecollect(partitions(n,m))
to get an array of all partitions. The number of partitions to generete can be efficiently computed usinglength(partitions(n,m))
.
-
partitions
(array) Generate all set partitions of the elements of an array, represented as arrays of arrays. Because the number of partitions can be very large, this function returns an iterator object. Use
collect(partitions(array))
to get an array of all partitions. The number of partitions to generete can be efficiently computed usinglength(partitions(array))
.
-
partitions
(array, m) Generate all set partitions of the elements of an array into exactly m subsets, represented as arrays of arrays. Because the number of partitions can be very large, this function returns an iterator object. Use
collect(partitions(array,m))
to get an array of all partitions. The number of partitions into m subsets is equal to the Stirling number of the second kind and can be efficiently computed usinglength(partitions(array,m))
.
Statistics¶
-
mean
(v[, region])¶ Compute the mean of whole array
v
, or optionally along the dimensions inregion
. Note: Julia does not ignoreNaN
values in the computation. For applications requiring the handling of missing data, theDataArray
package is recommended.
-
mean!
(r, v)¶ Compute the mean of
v
over the singleton dimensions ofr
, and write results tor
.
-
std
(v[, region])¶ Compute the sample standard deviation of a vector or array
v
, optionally along dimensions inregion
. The algorithm returns an estimator of the generative distribution’s standard deviation under the assumption that each entry ofv
is an IID drawn from that generative distribution. This computation is equivalent to calculatingsqrt(sum((v - mean(v)).^2) / (length(v) - 1))
. Note: Julia does not ignoreNaN
values in the computation. For applications requiring the handling of missing data, theDataArray
package is recommended.
-
stdm
(v, m)¶ Compute the sample standard deviation of a vector
v
with known meanm
. Note: Julia does not ignoreNaN
values in the computation.
-
var
(v[, region])¶ Compute the sample variance of a vector or array
v
, optionally along dimensions inregion
. The algorithm will return an estimator of the generative distribution’s variance under the assumption that each entry ofv
is an IID drawn from that generative distribution. This computation is equivalent to calculatingsum((v - mean(v)).^2) / (length(v) - 1)
. Note: Julia does not ignoreNaN
values in the computation. For applications requiring the handling of missing data, theDataArray
package is recommended.
-
varm
(v, m)¶ Compute the sample variance of a vector
v
with known meanm
. Note: Julia does not ignoreNaN
values in the computation.
-
median
(v; checknan::Bool=true)¶ Compute the median of a vector
v
. If keyword argumentchecknan
is true (the default), an error is raised for data containing NaN values. Note: Julia does not ignoreNaN
values in the computation. For applications requiring the handling of missing data, theDataArray
package is recommended.
-
median!
(v; checknan::Bool=true)¶ Like
median
, but may overwrite the input vector.
-
hist
(v[, n]) → e, counts¶ Compute the histogram of
v
, optionally using approximatelyn
bins. The return values are a rangee
, which correspond to the edges of the bins, andcounts
containing the number of elements ofv
in each bin. Note: Julia does not ignoreNaN
values in the computation.
-
hist
(v, e) → e, counts Compute the histogram of
v
using a vector/rangee
as the edges for the bins. The result will be a vector of lengthlength(e) - 1
, such that the element at locationi
satisfiessum(e[i] .< v .<= e[i+1])
. Note: Julia does not ignoreNaN
values in the computation.
-
hist!
(counts, v, e) → e, counts¶ Compute the histogram of
v
, using a vector/rangee
as the edges for the bins. This function writes the resultant counts to a pre-allocated arraycounts
.
-
hist2d
(M, e1, e2) -> (edge1, edge2, counts)¶ Compute a “2d histogram” of a set of N points specified by N-by-2 matrix
M
. Argumentse1
ande2
are bins for each dimension, specified either as integer bin counts or vectors of bin edges. The result is a tuple ofedge1
(the bin edges used in the first dimension),edge2
(the bin edges used in the second dimension), andcounts
, a histogram matrix of size(length(edge1)-1, length(edge2)-1)
. Note: Julia does not ignoreNaN
values in the computation.
-
hist2d!
(counts, M, e1, e2) -> (e1, e2, counts)¶ Compute a “2d histogram” with respect to the bins delimited by the edges given in
e1
ande2
. This function writes the results to a pre-allocated arraycounts
.
-
histrange
(v, n)¶ Compute nice bin ranges for the edges of a histogram of
v
, using approximatelyn
bins. The resulting step sizes will be 1, 2 or 5 multiplied by a power of 10. Note: Julia does not ignoreNaN
values in the computation.
-
midpoints
(e)¶ Compute the midpoints of the bins with edges
e
. The result is a vector/range of lengthlength(e) - 1
. Note: Julia does not ignoreNaN
values in the computation.
-
quantile
(v, p)¶ Compute the quantiles of a vector
v
at a specified set of probability valuesp
. Note: Julia does not ignoreNaN
values in the computation.
-
quantile
(v, p) Compute the quantile of a vector
v
at the probabilityp
. Note: Julia does not ignoreNaN
values in the computation.
-
quantile!
(v, p)¶ Like
quantile
, but overwrites the input vector.
-
cov
(v1[, v2][, vardim=1, corrected=true, mean=nothing])¶ Compute the Pearson covariance between the vector(s) in
v1
andv2
. Here,v1
andv2
can be either vectors or matrices.This function accepts three keyword arguments:
vardim
: the dimension of variables. Whenvardim = 1
, variables are considered in columns while observations in rows; whenvardim = 2
, variables are in rows while observations in columns. By default, it is set to1
.corrected
: whether to apply Bessel’s correction (divide byn-1
instead ofn
). By default, it is set totrue
.mean
: allow users to supply mean values that are known. By default, it is set tonothing
, which indicates that the mean(s) are unknown, and the function will compute the mean. Users can usemean=0
to indicate that the input data are centered, and hence there’s no need to subtract the mean.
The size of the result depends on the size of
v1
andv2
. When bothv1
andv2
are vectors, it returns the covariance between them as a scalar. When either one is a matrix, it returns a covariance matrix of size(n1, n2)
, wheren1
andn2
are the numbers of slices inv1
andv2
, which depend on the setting ofvardim
.Note:
v2
can be omitted, which indicatesv2 = v1
.
-
cor
(v1[, v2][, vardim=1, mean=nothing])¶ Compute the Pearson correlation between the vector(s) in
v1
andv2
.Users can use the keyword argument
vardim
to specify the variable dimension, andmean
to supply pre-computed mean values.
Signal Processing¶
Fast Fourier transform (FFT) functions in Julia are largely implemented by calling functions from FFTW.
-
fft
(A[, dims])¶ Performs a multidimensional FFT of the array
A
. The optionaldims
argument specifies an iterable subset of dimensions (e.g. an integer, range, tuple, or array) to transform along. Most efficient if the size ofA
along the transformed dimensions is a product of small primes; seenextprod()
. See alsoplan_fft()
for even greater efficiency.A one-dimensional FFT computes the one-dimensional discrete Fourier transform (DFT) as defined by
\[\operatorname{DFT}(A)[k] = \sum_{n=1}^{\operatorname{length}(A)} \exp\left(-i\frac{2\pi (n-1)(k-1)}{\operatorname{length}(A)} \right) 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 onA
, which must be an array of complex floating-point numbers.
-
ifft
(A[, dims])¶ Multidimensional inverse FFT.
A one-dimensional inverse FFT computes
\[\operatorname{IDFT}(A)[k] = \frac{1}{\operatorname{length}(A)} \sum_{n=1}^{\operatorname{length}(A)} \exp\left(+i\frac{2\pi (n-1)(k-1)} {\operatorname{length}(A)} \right) 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 onA
.
-
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 efficient thanifft()
because it omits a scaling step, which in some applications can be combined with other computational steps elsewhere.)\[\operatorname{BDFT}(A)[k] = \operatorname{length}(A) \operatorname{IDFT}(A)[k]\]
-
bfft!
(A[, dims])¶ Same as
bfft()
, but operates in-place onA
.
-
plan_fft
(A[, dims[, flags[, timelimit]]])¶ Pre-plan an optimized FFT along given dimensions (
dims
) of arrays matching the shape and type ofA
. (The first two arguments have the same meaning as forfft()
.) Returns a functionplan(A)
that computesfft(A, dims)
quickly.The
flags
argument is a bitwise-or of FFTW planner flags, defaulting toFFTW.ESTIMATE
. e.g. passingFFTW.MEASURE
orFFTW.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 flags. The optionaltimelimit
argument specifies a rough upper bound on the allowed planning time, in seconds. PassingFFTW.MEASURE
orFFTW.PATIENT
may cause the input arrayA
to be overwritten with zeros during plan creation.plan_fft!()
is the same asplan_fft()
but creates a plan that operates in-place on its argument (which must be an array of complex floating-point numbers).plan_ifft()
and so on are similar but produce plans that perform the equivalent of the inverse transformsifft()
and so on.
-
plan_ifft
(A[, dims[, flags[, timelimit]]])¶ Same as
plan_fft()
, but produces a plan that performs inverse transformsifft()
.
-
plan_bfft
(A[, dims[, flags[, timelimit]]])¶ Same as
plan_fft()
, but produces a plan that performs an unnormalized backwards transformbfft()
.
-
plan_fft!
(A[, dims[, flags[, timelimit]]])¶ Same as
plan_fft()
, but operates in-place onA
.
-
plan_ifft!
(A[, dims[, flags[, timelimit]]])¶ Same as
plan_ifft()
, but operates in-place onA
.
-
plan_bfft!
(A[, dims[, flags[, timelimit]]])¶ Same as
plan_bfft()
, but operates in-place onA
.
-
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()
. IfA
has size(n_1, ..., n_d)
, the result has size(floor(n_1/2)+1, ..., n_d)
.The optional
dims
argument specifies an iterable subset of one or more dimensions ofA
to transform, similar tofft()
. Instead of (roughly) halving the first dimension ofA
in the result, thedims[1]
dimension is (roughly) halved in the same way.
-
irfft
(A, d[, dims])¶ Inverse of
rfft()
: for a complex arrayA
, gives the corresponding real array whose FFT yieldsA
in the first half. As forrfft()
,dims
is an optional subset of dimensions to transform, defaulting to1:ndims(A)
.d
is the length of the transformed real array along thedims[1]
dimension, which must satisfyd == floor(size(A,dims[1])/2)+1
. (This parameter cannot be inferred fromsize(A)
due to the possibility of rounding by thefloor
function here.)
-
brfft
(A, d[, dims])¶ Similar to
irfft()
but computes an unnormalized inverse transform (similar tobfft()
), 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.
-
plan_rfft
(A[, dims[, flags[, timelimit]]])¶ Pre-plan an optimized real-input FFT, similar to
plan_fft()
except forrfft()
instead offft()
. The first two arguments, and the size of the transformed result, are the same as forrfft()
.
-
plan_brfft
(A, d[, dims[, flags[, timelimit]]])¶ Pre-plan an optimized real-input unnormalized transform, similar to
plan_rfft()
except forbrfft()
instead ofrfft()
. The first two arguments and the size of the transformed result, are the same as forbrfft()
.
-
plan_irfft
(A, d[, dims[, flags[, timelimit]]])¶ Pre-plan an optimized inverse real-input FFT, similar to
plan_rfft()
except forirfft()
andbrfft()
, respectively. The first three arguments have the same meaning as forirfft()
.
-
dct
(A[, dims])¶ Performs a multidimensional type-II discrete cosine transform (DCT) of the array
A
, using the unitary normalization of the DCT. The optionaldims
argument specifies an iterable subset of dimensions (e.g. an integer, range, tuple, or array) to transform along. Most efficient if the size ofA
along the transformed dimensions is a product of small primes; seenextprod()
. See alsoplan_dct()
for even greater efficiency.
-
dct!
(A[, dims])¶ Same as
dct!()
, except that it operates in-place onA
, which must be an array of real or complex floating-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 optionaldims
argument specifies an iterable subset of dimensions (e.g. an integer, range, tuple, or array) to transform along. Most efficient if the size ofA
along the transformed dimensions is a product of small primes; seenextprod()
. See alsoplan_idct()
for even greater efficiency.
-
idct!
(A[, dims])¶ Same as
idct!()
, but operates in-place onA
.
-
plan_dct
(A[, dims[, flags[, timelimit]]])¶ Pre-plan an optimized discrete cosine transform (DCT), similar to
plan_fft()
except producing a function that computesdct()
. The first two arguments have the same meaning as fordct()
.
-
plan_dct!
(A[, dims[, flags[, timelimit]]])¶ Same as
plan_dct()
, but operates in-place onA
.
-
plan_idct
(A[, dims[, flags[, timelimit]]])¶ Pre-plan an optimized inverse discrete cosine transform (DCT), similar to
plan_fft()
except producing a function that computesidct()
. The first two arguments have the same meaning as foridct()
.
-
plan_idct!
(A[, dims[, flags[, timelimit]]])¶ Same as
plan_idct()
, but operates in-place onA
.
-
fftshift
(x)¶ Swap the first and second halves of each dimension of
x
.
-
fftshift
(x, dim) Swap the first and second halves of the given dimension of array
x
.
-
ifftshift
(x[, dim])¶ Undoes the effect of
fftshift
.
-
filt
(b, a, x[, si])¶ Apply filter described by vectors
a
andb
to vectorx
, with an optional initial filter state vectorsi
(defaults to zeros).
-
filt!
(out, b, a, x[, si])¶ Same as
filt()
but writes the result into theout
argument, which may alias the inputx
to modify it in-place.
-
deconv
(b, a)¶ Construct vector
c
such thatb = 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 vectorsu
andv
. Uses 2-D FFT algorithm
-
conv2
(B, A) 2-D convolution of the matrix
B
with the matrixA
. Uses 2-D FFT algorithm
-
xcorr
(u, v)¶ Compute the cross-correlation of two vectors.
The following functions are defined within the Base.FFTW
module.
-
r2r
(A, kind[, dims])¶ Performs a multidimensional real-input/real-output (r2r) transform of type
kind
of the arrayA
, as defined in the FFTW manual.kind
specifies either a discrete cosine transform of various types (FFTW.REDFT00
,FFTW.REDFT01
,FFTW.REDFT10
, orFFTW.REDFT11
), a discrete sine transform of various types (FFTW.RODFT00
,FFTW.RODFT01
,FFTW.RODFT10
, orFFTW.RODFT11
), a real-input DFT with halfcomplex-format output (FFTW.R2HC
and its inverseFFTW.HC2R
), or a discrete Hartley transform (FFTW.DHT
). Thekind
argument may be an array or tuple in order to specify different transform types along the different dimensions ofA
;kind[end]
is used for any unspecified dimensions. See the FFTW manual for precise definitions of these transform types, at http://www.fftw.org/doc.The optional
dims
argument specifies an iterable subset of dimensions (e.g. an integer, range, tuple, or array) to transform along.kind[i]
is then the transform type fordims[i]
, withkind[end]
being used fori > length(kind)
.See also
plan_r2r()
to pre-plan optimized r2r transforms.
-
r2r!
(A, kind[, dims])¶ Same as
r2r()
, but operates in-place onA
, which must be an array of real or complex floating-point numbers.
-
plan_r2r
(A, kind[, dims[, flags[, timelimit]]])¶ Pre-plan an optimized r2r transform, similar to
Base.plan_fft()
except that the transforms (and the first three arguments) correspond tor2r()
andr2r!()
, respectively.
-
plan_r2r!
(A, kind[, dims[, flags[, timelimit]]])¶ Similar to
Base.plan_fft()
, but corresponds tor2r!()
.
Numerical Integration¶
Although several external packages are available for numeric integration and solution of ordinary differential equations, 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)
froma
tob
, and optionally over additional intervalsb
toc
and so on. Keyword options include a relative error tolerancereltol
(defaults tosqrt(eps)
in the precision of the endpoints), an absolute error toleranceabstol
(defaults to 0), a maximum number of function evaluationsmaxevals
(defaults to10^7
), and theorder
of the integration rule (defaults to 7).Returns a pair
(I,E)
of the estimated integralI
and an estimated upper bound on the absolute errorE
. Ifmaxevals
is not exceeded thenE <= max(abstol, reltol*norm(I))
will hold. (Note that it is useful to specify a positiveabstol
in cases wherenorm(I)
may be zero.)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 areBigFloat
, then the integration will be performed inBigFloat
precision as well (note: it is advisable to increase the integrationorder
in rough proportion to the precision, for smooth integrands). More generally, the precision is set by the precision of the integration endpoints (promoted to floating-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 anorm
(i.e., any normed vector space). Alternatively, a different norm can be specified 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 atx=0.7
and you want to integrate from 0 to 1, you should usequadgk(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, alog(x)
or1/sqrt(x)
singularity).For real-valued endpoints, the starting and/or ending points may be infinite. (A coordinate transformation is performed internally to map the infinite interval to a finite one.)
Parallel Computing¶
-
addprocs
(n; cman::ClusterManager=LocalManager()) → List of process identifiers¶ 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 packageClusterManagers
.See the documentation for package
ClusterManagers
for more information on how to write a custom cluster manager.
-
addprocs
(machines; tunnel=false, dir=JULIA_HOME, sshflags::Cmd=``) → List of process identifiers 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 file system.
machines
is a vector of host definitions 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
: iftrue
then SSH tunneling will be used to connect to the worker.dir
: specifies the location of the julia binaries on the worker nodes.sshflags
: specifies 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 identifiers.
-
workers
()¶ Returns a list of all worker process identifiers.
-
rmprocs
(pids...)¶ Removes the specified workers.
-
interrupt
([pids...])¶ Interrupt the current executing task on the specified 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 applyingf
to each element in parallel. Ifnprocs() > 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 off
on a different worker. Iferr_stop
is true, it takes precedence over the value oferr_retry
andpmap
stops execution on the first error.
-
remotecall
(id, func, args...)¶ Call a function asynchronously on the given arguments on the specified 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 specified remote reference.Condition
: Wait fornotify
on a condition.Process
: Wait for a process or process chain to exit. Theexitcode
field of a process can be used to determine success or failure.Task
: Wait for aTask
to finish, returning its result value.RawFD
: Wait for changes on a file descriptor (see poll_fd for keyword arguments and return code)
If no argument is passed, the task blocks for an undefined period. If the task’s state is set to
:waiting
, it can only be restarted by an explicit call toschedule
oryieldto
. If the task’s state is:runnable
, it might be restarted unpredictably.Often
wait
is called within awhile
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 first 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 aRemoteRef
that is assigned once.If the argument
RemoteRef
is owned by a different node, this call will block to wait for the answer. It is recommended to wait forr
in a separate task instead, or to use a localRemoteRef
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
returnstrue
or forsecs`
seconds, whichever is earlier.testcb
is polled everypollint
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 processp
, returning aRemoteRef
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 specified range is partitioned and locally executed across all workers. In case an optional reducer function is specified, @parallel performs local reductions on each worker with a final 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, prefix the call with
@sync
, like@sync @parallel for var = range body end
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 specified indices.dims
is the overall size of the distributed array.procs
optionally specifies a vector of process IDs to use. If unspecified, 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 fills it with a valuev
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 filled with value
x
. Trailing arguments are the same as those accepted byDArray()
.
-
drand
(dims, ...)¶ Construct a distributed uniform random array. 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
.
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)
. Ifmode
is"r"
, thenstream
reads from the process’s standard output andstdio
optionally specifies the process’s standard input stream. Ifmode
is"w"
, thenstream
writes to the process’s standard input andstdio
optionally specifies the process’s standard output stream.
-
open
(f::Function, command, mode::String="r", stdio=DevNull) Similar to
open(command, mode, stdio)
, but callsf(stream)
on the resulting read or write stream, then closes the stream and waits for the process to complete. Returns the value returned byf
.
-
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, filename) -
|>
(filename, command) Redirect operator. Used for piping the output of a process into another (first form) or to redirect the standard output/input of a command to/from a file (second and third forms).
- Examples:
run(`ls` |> `grep xyz`)
run(`ls` |> "out.txt")
run("out.txt" |> `grep xyz`)
-
>>
(command, filename) Redirect standard output of a process, appending to the destination file.
-
.>
(command, filename) Redirect the standard error stream of a process.
-
gethostname
() → String¶ Get the local machine’s 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 specified) and applies function f before returning.
-
mkdir
(path[, mode])¶ Make a new directory with name
path
and permissionsmode
.mode
defaults to 0o777, modified by the current file creation mask.
-
mkpath
(path[, mode])¶ Create all directories in the given
path
, with permissionsmode
.mode
defaults to 0o777, modified by the current file creation mask.
-
symlink
(target, link)¶ Creates a symbolic link to
target
with the namelink
.注解
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
tomode
. Only integermode
s (e.g. 0o777) are currently supported.
-
getpid
() → Int32¶ Get julia’s 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 undefined, 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 totime
to convert it to seconds since the epoch, theisdst
field should be filled 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 fields
sec
,min
,hour
,mday
,month
,year
,wday
,yday
, andisdst
.
-
tic
()¶ Set a timer to be read by the next call to
toc()
ortoq()
. 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 floating-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
, doa
on Unix systems (including Linux and OS X) andb
elsewhere. See documentation for Handling Platform Variations in the Calling C and Fortran Code section of the manual.
-
@osx
()¶ Given
@osx? a : b
, doa
on OS X andb
elsewhere. See documentation for Handling Platform Variations in the Calling C and Fortran Code section of the manual.
-
@linux
()¶ Given
@linux? a : b
, doa
on Linux andb
elsewhere. See documentation for Handling Platform Variations in the Calling C and Fortran Code section of the manual.
-
@windows
()¶ Given
@windows? a : b
, doa
on Windows andb
elsewhere. See documentation for Handling Platform Variations in the Calling C and Fortran Code section of the manual.
C Interface¶
-
ccall
((symbol, library) or fptr, RetType, (ArgType1, ...), ArgVar1, ...)¶ Call function in C-exported shared library, specified 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.
-
cglobal
((symbol, library) or ptr[, Type=Void])¶ Obtain a pointer to a global variable in a C-exported shared library, specified exactly as in
ccall
. Returns aPtr{Type}
, defaulting toPtr{Void}
if no Type argument is supplied. The values can be read or written byunsafe_load
orunsafe_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
(libfile::String[, flags::Integer])¶ Load a shared library, returning an opaque handle.
The optional flags argument is a bitwise-or of zero or more of
RTLD_LOCAL
,RTLD_GLOBAL
,RTLD_LAZY
,RTLD_NOW
,RTLD_NODELETE
,RTLD_NOLOAD
,RTLD_DEEPBIND
, andRTLD_FIRST
. These are converted to the corresponding flags of the POSIX (and/or GNU libc and/or MacOS) dlopen command, if possible, or are ignored if the specified functionality is not available on the current platform. The default isRTLD_LAZY|RTLD_DEEPBIND|RTLD_LOCAL
. An important usage of these flags, on POSIX platforms, is to specifyRTLD_LAZY|RTLD_DEEPBIND|RTLD_GLOBAL
in order for the library’s symbols to be available for usage in other shared libraries, in situations where there are dependencies between shared libraries.
-
dlopen_e
(libfile::String[, flags::Integer])¶ Similar to
dlopen()
, except returns aNULL
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.
-
dlclose
(handle)¶ Close shared library referenced by handle.
-
find_library
(names, locations)¶ Searches for the first library in
names
in the paths in thelocations
list,DL_LOAD_PATH
, or system library paths (in that order) which can successfully be dlopen’d. On success, the return value will be one of the names (potentially prefixed by one of the paths in locations). This string can be assigned to aglobal const
and used as the library name in futureccall
‘s. On failure, it returns the empty string.
-
DL_LOAD_PATH
¶ When calling
dlopen
, the paths in this list will be searched first, 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 atp
. This is equivalent to the C expressionp[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 atp
. This is equivalent to the C expressionp[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 offsetso
in the source anddo
in the destination (1-indexed).
-
copy!
(dest, src)¶ Copy all elements from collection
src
to arraydest
. Returnsdest
.
-
copy!
(dest, do, src, so, N) Copy
N
elements from collectionsrc
starting at offsetso
, to arraydest
starting at offsetdo
. Returnsdest
.
-
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 specified 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 specifies whether Julia should take ownership of the memory, callingfree
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 resultingPtr
will not protect the object from garbage collection, so you must ensure that the object remains referenced for the whole time that thePtr
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, undefined 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. Intended 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 library’s
errno
. If an argument is specified, it is used to set the value oferrno
.The value of
errno
is only valid immediately after accall
to a C library routine that sets it. Specifically, you cannot callerrno
at the next prompt in a REPL, because lots of code is executed between prompts.
-
systemerror
(sysfunc, iftrue)¶ Raises a
SystemError
forerrno
with the descriptive stringsysfunc
ifbool
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)
-
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)
Errors¶
-
error
(message::String)¶ Raise an error with the given message
-
throw
(e)¶ Throw an object as an exception
-
rethrow
([e])¶ Throw an 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 file or stream.
-
ErrorException
¶ Generic error type. The error message, in the .msg field, may provide more specific details.
-
KeyError
¶ An indexing operation into an
Associative
(Dict
) orSet
like object tried to access or delete a non-existent element.
-
LoadError
¶ An error occurred while including, requiring, or using a file. The error specifics should be available in the .error field.
-
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.
Tasks¶
-
Task
(func)¶ Create a
Task
(i.e. thread, or coroutine) to execute the given function (which must be callable with no arguments). The task exits when this function returns.
-
yieldto
(task, args...)¶ Switch to the given task. The first time a task is switched to, the task’s function is called with no arguments. On subsequent switches,
args
are returned from the task’s last call toyieldto
. 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 specified task. Additional arguments may be passed, to be returned from the lastproduce
call in the producer.
-
produce
(value)¶ Send the given value to the last
consume
call, switching to the consumer task. If the nextconsume
call passes any values, they are returned byproduce
.
-
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 task’s task-local storage.
-
task_local_storage
(symbol, value) Assign a value to a symbol in the current task’s task-local storage.
-
task_local_storage
(body, symbol, value) Call the function
body
with a modified task-local storage, in whichvalue
is assigned tosymbol
; the previous value ofsymbol
, 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 aCondition
are suspended and queued. Tasks are woken up whennotify
is later called on theCondition
. Edge triggering means that only tasks waiting at the timenotify
is called can be woken up. For level-triggered notifications, you must keep extra state to keep track of whether a notification has happened. TheRemoteRef
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
. Ifall
is true (the default), all waiting tasks are woken, otherwise only one is. Iferror
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 scheduler’s 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. Iferror
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 scheduler’s 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 specified number of seconds. The minimum sleep time is 1 millisecond or input of
0.001
.
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
andstop_timer
.
-
start_timer
(t::Timer, delay, repeat)¶ Start invoking the callback for a
Timer
after the specified initial delay, and then repeating with the given interval. Times are in seconds. Ifrepeat
is0
, the timer is only triggered once.
-
stop_timer
(t::Timer)¶ Stop invoking the callback for a timer.
Reflection¶
-
module_name
(m::Module) → Symbol¶ Get the name of a module as a symbol.
-
module_parent
(m::Module) → Module¶ Get a module’s 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-qualified name of a module as a tuple of symbols. For example,
fullname(Base.Pkg)
gives(:Base,:Pkg)
, andfullname(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.
-
names
(x::DataType) Get an array of the fields 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 iscurrent_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 definition of a generic function.
-
functionloc
(f::Function, types)¶ Returns a tuple
(filename,line)
giving the location of a method definition.
-
functionlocs
(f::Function, types)¶ Returns an array of the results of
functionloc
for all matching definitions.
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.
-
@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.