Getting Around¶
-
exit
([code])¶ Quit (or control-D at the prompt). The default exit code is zero, indicating that the processes completed successfully.
-
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. If the file name ends in ”.jl” it is reloaded when the editor closes the file.
-
edit
(function[, types]) Edit the definition of a function, optionally specifying a tuple of types to indicate which method to edit. When the editor exits, the source file containing the definition is reloaded.
-
require
(file::String...)¶ Load source files once, in the context of the
Main
module, on every active node, searching the system-wideLOAD_PATH
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.
-
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.
-
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.
-
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, args...)¶ Show which method of
f
will be called for the given arguments.
-
methods
(f)¶ Show all methods of
f
with their argument types.
-
methodswith
(typ[, showparents])¶ Show all methods with an argument of type
typ
. If optionalshowparents
istrue
, also show arguments with a parent type oftyp
, excluding typeAny
.
All Objects¶
-
is
(x, y)¶ Determine whether
x
andy
are identical, in the sense that no program could distinguish them.
-
isa
(x, type)¶ Determine whether
x
is of the given type.
-
isequal
(x, y)¶ True if and only if
x
andy
have the same contents. Loosely speaking, this meansx
andy
would look the same when printed.
-
isless
(x, y)¶ Test whether
x
is less thany
. Provides a total order consistent withisequal
. 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 that can be ordered should implement this function.
-
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)¶ Compute an integer hash code such that
isequal(x,y)
implieshash(x)==hash(y)
.
-
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.
-
convert
(type, x)¶ Try to convert
x
to the given type.
-
promote
(xs...)¶ Convert all arguments to their common promotion type (if any), and return them all (as a tuple).
Types¶
-
subtype
(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
subtype(T1,T2)
.
-
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-denormal 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
. The only types that are sensible arguments areFloat32
andFloat64
. 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.
-
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)
.
-
fieldtype
(value, name::Symbol)¶ Determine the declared type of a named field in a value of composite type.
Generic Functions¶
-
method_exists
(f, tuple) → Bool¶ Determine whether the given generic function has a method matching the given tuple of argument types.
Example:
method_exists(length, (Array,)) = true
-
applicable
(f, args...)¶ Determine whether the given generic function has a method applicable to the given arguments.
-
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 which allows for easy function chaining.
Example:
[1:5] | x->x.^2 | sum | inv
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 it’s own inverse:[zip(zip(a...)...)...] == [a...]
.
-
enumerate
(iter)¶ Return an iterator that yields
(i, x)
wherei
is an index starting at 1, andx
is theith
value from the given iterator.
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).
-
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.
Example:
endof([1,2,4]) = 3
Fully implemented by: Range
, Range1
, Tuple
, Number
, AbstractArray
, IntSet
, Dict
, WeakKeyDict
, String
, Set
.
Iterable Collections¶
-
contains
(itr, x) → Bool¶ Determine whether a collection contains the given value,
x
.
-
findin
(a, b)¶ Returns the indices of elements in collection
a
that appear in collectionb
-
unique
(itr)¶ Returns an array containing only the unique elements of the iterable
itr
.
-
reduce
(op, v0, itr)¶ Reduce the given collection with the given operator, i.e. accumulate
v = op(v,elt)
for each element, wherev
starts asv0
. Reductions for certain commonly-used operators are available in a more convenient 1-argument form:max(itr)
,min(itr)
,sum(itr)
,prod(itr)
,any(itr)
,all(itr)
.
-
max
(itr)¶ Returns the largest element in a collection
-
min
(itr)¶ Returns the smallest element in a collection
-
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
-
findmin
(itr) → (x, index)¶ Returns the minimum element and its index
-
sum
(itr)¶ Returns the sum of all elements in a collection
-
prod
(itr)¶ Returns the product of all elements of a collection
-
any
(itr) → Bool¶ Test whether any elements of a boolean collection are true
-
all
(itr) → Bool¶ Test whether all elements of a boolean collection are true
-
count
(itr) → Integer¶ Count the number of boolean elements in
itr
which are true.
-
countp
(p, itr) → Integer¶ Count the number of elements in
itr
for which predicatep
is true.
-
any
(p, itr) → Bool Determine whether any element of
itr
satisfies the given predicate.
-
all
(p, itr) → Bool Determine whether all elements of
itr
satisfy the given predicate.
-
map
(f, c) → collection¶ Transform collection
c
by applyingf
to each element.Example:
map((x) -> x * 2, [1, 2, 3]) = [2, 4, 6]
-
map!
(function, collection)¶ In-place version of
map()
.
-
mapreduce
(f, op, itr)¶ Applies function
f
to each element initr
and then reduces the result using the binary functionop
.Example:
mapreduce(x->x^2, +, [1:3]) == 1 + 4 + 9 == 14
-
first
(coll)¶ Get the first element of an ordered collection.
-
last
(coll)¶ Get the last element of an ordered collection.
-
collect
(collection)¶ Return an array of all items in a collection. For associative collections, returns (key, value) tuples.
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
, 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}
.
-
Dict{K,V}
()¶ Construct a hashtable with keys of type K and values of type V
-
has
(collection, key)¶ 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.
-
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.
-
keys
(collection)¶ Return an array of all keys in a collection.
-
values
(collection)¶ Return an array of all values in a collection.
-
merge
(collection, others...)¶ Construct a merged collection from the given collections.
-
merge!
(collection, others...)¶ Update collection with pairs from the other collections
-
filter
(function, collection)¶ Return a copy of collection, removing (key, value) pairs for which function is false.
-
filter!
(function, collection)¶ Update collection, removing (key, value) pairs for which function is false.
-
eltype
(collection)¶ Returns the type tuple of the (key,value) pairs contained in collection.
-
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
.
Set-Like Collections¶
-
add!
(collection, key)¶ Add an element to a set-like collection.
-
add_each!
(collection, iterable)¶ Adds each element in iterable to the collection.
-
Set
(x...)¶ Construct a
Set
with the given elements. Should be used instead ofIntSet
for sparse integer sets.
-
IntSet
(i...)¶ Construct an
IntSet
of the given integers. Implemented as a bit string, and therefore good for dense integer sets.
-
union
(s1, s2...)¶ Construct the union of two or more sets. Maintains order with arrays.
-
union!
(s1, s2)¶ Constructs the union of IntSets s1 and s2, stores the result in
s1
.
-
intersect
(s1, s2...)¶ Construct the intersection of two or more sets. Maintains order with arrays.
-
setdiff
(s1, s2)¶ Construct the set of elements in
s1
but nots2
. Maintains order with arrays.
-
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.
-
del_each!
(s, itr)¶ Deletes each element of itr in set s in-place.
-
intersect!
(s1, s2)¶ Intersects IntSets s1 and s2 and overwrites the set s1 with the result. If needed, s1 will be expanded to the size of s2.
Fully implemented by: IntSet
, Set
.
Partially implemented by: Array
.
Dequeues¶
-
push!
(collection, item) → collection¶ Insert an item at the end of a collection.
-
pop!
(collection) → item¶ Remove the last item in a collection and return it.
-
unshift!
(collection, item) → collection¶ Insert an item 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.
-
delete!
(collection, index) → item Remove the item at the given index, and return the deleted item.
-
delete!
(collection, range) → items Remove items at specified range, and return a collection containing the deleted items.
-
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.
Fully implemented by: Vector
(aka 1-d Array
).
Strings¶
-
length
(s) The number of characters in string
s
.
-
*
(s, t)¶ Concatenate strings.
Example:
"Hello " * "world" == "Hello world"
-
^
(s, n)¶ Repeat string
s
n
times.Example:
"Julia "^3 == "Julia Julia Julia "
-
string
(xs...)¶ Create a string from any values using the
print
function.
-
repr
(x)¶ Create a string from any value using the
show
function.
-
bytestring
(::Ptr{Uint8})¶ Create a string from the address of a C (0-terminated) string. A copy is made; the ptr can be safely freed.
-
bytestring
(s) Convert a string to a contiguous byte array representation appropriate for passing it to C functions.
-
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).
-
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.
-
ismatch
(r::Regex, s::String)¶ Test whether a string contains a match of the given regular expression.
-
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 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
. The return value is0:-1
if there is no match.
-
replace
(string, pat, r[, n])¶ Search for the given pattern
pat
, and replace each occurance withr
. Ifn
is provided, replace at mostn
occurances. 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 strings 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.
-
strip
(string[, chars])¶ Return
string
with any leading and trailing whitespace removed. If a stringchars
is provided, instead remove characters contained in that string.
-
lstrip
(string[, chars])¶ Return
string
with any leading whitespace removed. If a stringchars
is provided, instead remove characters contained in that string.
-
rstrip
(string[, chars])¶ Return
string
with any trailing whitespace removed. If a stringchars
is provided, instead remove characters contained in that string.
-
beginswith
(string, prefix)¶ Returns
true
ifstring
starts withprefix
.
-
endswith
(string, suffix)¶ Returns
true
ifstring
ends withsuffix
.
-
uppercase
(string)¶ Returns
string
with all characters converted to uppercase.
-
lowercase
(string)¶ Returns
string
with all characters 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
. Returnsendof(str)+1
at the end of the string.
-
prevind
(str, i)¶ Get the previous valid string index before
i
. Returns0
at the beginning of the string.
-
thisind
(str, i)¶ Adjust
i
downwards until it reaches a valid index for the given 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::Char)¶ Tests whether a character is alphanumeric.
-
isalpha
(c::Char)¶ Tests whether a character is alphabetic.
-
isascii
(c::Char)¶ Tests whether a character belongs to the ASCII character set.
-
isblank
(c::Char)¶ Tests whether a character is a tab or space.
-
iscntrl
(c::Char)¶ Tests whether a character is a control character.
-
isdigit
(c::Char)¶ Tests whether a character is a numeric digit (0-9).
-
isgraph
(c::Char)¶ Tests whether a character is printable, and not a space.
-
islower
(c::Char)¶ Tests whether a character is a lowercase letter.
-
isprint
(c::Char)¶ Tests whether a character is printable, including space.
-
ispunct
(c::Char)¶ Tests whether a character is printable, and not a space or alphanumeric.
-
isspace
(c::Char)¶ Tests whether a character is any whitespace character.
-
isupper
(c::Char)¶ Tests whether a character is an uppercase letter.
-
isxdigit
(c::Char)¶ Tests whether a character is a valid hexadecimal digit.
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.
-
OUTPUT_STREAM
¶ The default stream used for text output, e.g. in the
print
andshow
functions.
-
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")
-
memio
([size[, finalize::Bool]]) → IOStream¶ Create an in-memory I/O stream, optionally specifying how much initial space is needed.
-
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.
-
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.
-
position
(s)¶ Get the current position of a stream.
-
seek
(s, pos)¶ Seek a stream to the given position.
-
seek_end
(s)¶ Seek a stream to the end.
-
skip
(s, offset)¶ Seek a stream relative to the current position.
-
eof
(stream)¶ 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
.
-
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.
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.
-
print
(x)¶ Write (to the default output stream) a canonical (un-decorated) text representation of a value if there is one, otherwise call
show
.
-
println
(x)¶ Print (using
print()
)x
followed by a newline
-
@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.
-
showall
(x)¶ Show x, printing all elements of arrays
-
dump
(x)¶ Write a thorough text representation of a value to the current output stream.
-
readall
(stream)¶ Read the entire contents of an I/O stream as a string.
-
readline
(stream)¶ Read a single line of text, including a trailing newline character (if one is reached before the end of the input).
-
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
(filename, delim::Char)¶ Read a matrix from a text file where each line gives one row, with elements separated by the given delimeter. 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
(filename, delim::Char, T::Type) Read a matrix from a text file with a given element type. 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
.
-
writedlm
(filename, array, delim::Char)¶ Write an array to a text file using the given delimeter (defaults to comma).
-
readcsv
(filename[, T::Type])¶ Equivalent to
readdlm
withdelim
set to comma.
-
writecsv
(filename, array)¶ Equivalent to
writedlm
withdelim
set to comma.
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 (no format conversions are possible), and dims is a tuple containing the size of the array.
The file is specified via the stream. 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.
Example: A = mmap_array(Int64, (25,30000), s)
This would create a 25-by-30000 array of Int64s, linked to the file associated with stream s.
-
msync
(array)¶ Forces synchronization between the in-memory version of a memory-mapped array and the on-disk version. You may not need to call this function, because synchronization is performed at intervals automatically by the operating system. Hower, you can call this directly if, for example, you are concerned about losing the result of a long-running calculation.
-
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
Float32
Float64
Complex64
Complex128
Mathematical Functions¶
-
-
(x)¶ Unary minus operator.
-
+
(x, y)¶ Binary addition operator.
-
-
(x, y) Binary subtraction operator.
-
*
(x, y) Binary multiplication operator.
-
/
(x, y)¶ Binary left-division operator.
-
\
(x, y)¶ Binary right-division operator.
-
^
(x, y) Binary exponentiation operator.
-
.+
(x, y)¶ Element-wise binary addition operator.
-
.-
(x, y)¶ Element-wise binary subtraction operator.
-
.*
(x, y)¶ Element-wise binary multiplication operator.
-
./
(x, y)¶ Element-wise binary left division operator.
-
.\
(x, y)¶ Element-wise binary right division operator.
-
.^
(x, y)¶ Element-wise binary 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)
-
rem
(x, m)¶ Remainder after division
-
%
(x, m)¶ Remainder after division. The operator form of
rem
.
-
mod1
(x, m)¶ Modulus after division, returning in the range (0,m]
-
//
(num, den)¶ Rational division
-
num
(x)¶ Numerator of the rational representation of
x
-
den
(x)¶ Denominator of the rational representation of
x
-
<<
(x, n)¶ Left shift operator.
-
>>
(x, n)¶ Right shift operator.
-
>>>
(x, n)¶ Unsigned right 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.
-
==
(x, y)¶ Equality comparison operator.
-
!=
(x, y)¶ Not-equals comparison operator.
-
<
(x, y)¶ Less-than comparison operator.
-
<=
(x, y)¶ Less-than-or-equals comparison operator.
-
>
(x, y)¶ Greater-than comparison operator.
-
>=
(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<y
,x==y
, orx>y
, respectively
-
!
(x)¶ Boolean not
-
~
(x)¶ Bitwise not
-
&
(x, y)¶ Bitwise and
-
|
(x, y) Bitwise or
-
$
(x, y)¶ Bitwise exclusive or
-
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
-
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 cotangent 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)
.
-
degrees2radians
(x)¶ Convert
x
from degrees to radians
-
radians2degrees
(x)¶ Convert
x
from radians to degrees
-
hypot
(x, y)¶ Compute the \(\sqrt{x^2+y^2}\) without undue overflow or underflow
-
log
(x)¶ Compute the natural logarithm of
x
-
log2
(x)¶ Compute the natural logarithm of
x
to base 2
-
log10
(x)¶ Compute the natural logarithm of
x
to base 10
-
log1p
(x)¶ Accurate natural logarithm of
1+x
-
frexp
(val, exp)¶ Return a number
x
such that it 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\)
-
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\)
-
square
(x)¶ Compute \(x^2\)
-
round
(x[, digits[, base]]) → FloatingPoint¶ round(x)
returns the nearest integer 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, 3, 2)
is3.125
.
-
ceil
(x[, digits[, base]]) → FloatingPoint¶ Returns the nearest integer not less than
x
.digits
andbase
work as above.
-
floor
(x[, digits[, base]]) → FloatingPoint¶ Returns the nearest integer not greater than
x
.digits
andbase
work as above.
-
trunc
(x[, digits[, base]]) → FloatingPoint¶ Returns the nearest integer not greater in magnitude than
x
.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]) → FloatingPoint¶ 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
x
andy
-
max
(x, y) Return the maximum of
x
andy
-
clamp
(x, lo, hi)¶ Return x if
lo <= x <= y
. Ifx < lo
, returnlo
. Ifx > hi
, returnhi
.
-
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}\)
-
cbrt
(x)¶ Return \(x^{1/3}\)
-
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)\).
-
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
cos(z) + i*sin(z)
if z is real. Return(cos(real(z)) + i*sin(real(z)))/exp(imag(z))
ifz
is complex
-
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)¶ 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.Example: \(100=2*2*5*5\); then,
factor(100) -> [5=>2,2=>2]
-
gcd
(x, y)¶ Greatest common divisor
-
lcm
(x, y)¶ Least common multiple
-
gcdx
(x, y)¶ Greatest common divisor, also returning integer coefficients
u
andv
that solveux+vy == gcd(x,y)
-
ispow2
(n)¶ Test whether
n
is a power of two
-
nextpow2
(n)¶ Next power of two not less than
n
-
prevpow2
(n)¶ Previous power of two not greater than
n
-
nextpow
(a, n)¶ Next power of
a
not less thann
-
prevpow
(a, n)¶ Previous power of
a
not greater thann
-
nextprod
([a, b, c, ]n)¶ Next integer not less than
n
that can be writtena^i1 * b^i2 * c^i3
for integersi1
,i2
,i3
.
-
prevprod
([a, b, c, ]n)¶ Previous integer not greater than
n
that can be writtena^i1 * b^i2 * c^i3
for integersi1
,i2
,i3
.
-
invmod
(x, m)¶ Inverse of
x
, modulom
-
powermod
(x, p, m)¶ Compute
mod(x^p, m)
-
gamma
(x)¶ Compute the gamma function of
x
-
lgamma
(x)¶ Compute the logarithm of
gamma(x)
-
lfact
(x)¶ Compute the logarithmic factorial of
x
-
digamma
(x)¶ Compute the digamma function of
x
(the logarithmic derivative 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)\).
-
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)\).
-
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)\).
-
hankelh1
(nu, x)¶ Bessel function of the third kind of order
nu
, \(H^{(1)}_\nu(x)\).
-
hankelh2
(nu, x)¶ Bessel function of the third kind of order
nu
, \(H^{(2)}_\nu(x)\).
-
besseli
(nu, x)¶ Modified Bessel function of the first kind of order
nu
, \(I_\nu(x)\).
-
besselk
(nu, x)¶ Modified Bessel function of the second kind of order
nu
, \(K_\nu(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 beta function \(\log(\operatorname{B}(x,y))\).
-
eta
(x)¶ Dirichlet eta function \(\eta(s) = \sum^\infty_{n=1}(-)^{n-1}/n^{s}\).
-
zeta
(x)¶ Riemann zeta function \(\zeta(s)\).
-
bitmix
(x, y)¶ Hash two integers into a single integer. Useful for constructing hash functions.
-
ndigits
(n, b)¶ Compute the number of digits in number
n
written in baseb
.
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.
-
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.
-
bool
(x)¶ Convert a number or numeric array to boolean
-
isbool
(x)¶ Test whether number or array is 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.
-
isinteger
(x)¶ Test whether a number or array is of integer type
-
signed
(x)¶ Convert a number to a signed integer
-
unsigned
(x)¶ 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
-
float32
(x)¶ Convert a number or array to
Float32
data type
-
float64
(x)¶ Convert a number or array to
Float64
data type
-
float
(x)¶ Convert a number, array, or string to a
FloatingPoint
data type. For numeric data, the smallest suitableFloatingPoint
type is used. For strings, it converts toFloat64
.
-
significand
(x)¶ Extract the significand(s) (a.k.a. mantissa), in binary representation, of a floating-point number or array.
For example,
significand(15.2)/15.2 == 0.125
, andsignificand(15.2)*8 == 15.2
-
exponent
(x) → Int¶ Get the exponent of a normalized floating-point number.
-
float64_valued
(x::Rational)¶ True if
x
can be losslessly represented as aFloat64
data type
-
complex64
(r, i)¶ Convert to
r+i*im
represented as aComplex64
data type
-
complex128
(r, i)¶ Convert to
r+i*im
represented as aComplex128
data type
-
char
(x)¶ Convert a number or array to
Char
data type
-
complex
(r, i)¶ Convert real numbers or arrays to complex
-
iscomplex
(x) → Bool¶ Test whether a number or array is of a complex type
-
isreal
(x) → Bool¶ Test whether a number or array is of a real 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
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
-
Inf
¶ Positive infinity of type Float64
-
Inf32
¶ Positive infinity of type Float32
-
NaN
¶ A not-a-number value of type Float64
-
NaN32
¶ A not-a-number value of type Float32
-
isdenormal
(f) → Bool¶ Test whether a floating point number is denormal
-
isfinite
(f) → Bool¶ Test whether a number is finite
-
isinf
(f)¶ Test whether a number is infinite
-
isnan
(f)¶ Test whether a floating point number is not a number (NaN)
-
inf
(f)¶ Returns infinity in the same floating point type as
f
(orf
can by the type itself)
-
nan
(f)¶ Returns NaN in the same floating point type as
f
(orf
can by the type itself)
-
nextfloat
(f)¶ Get the next floating point number in lexicographic order
-
prevfloat
(f) → Float¶ Get the previous floating point number in lexicographic order
-
integer_valued
(x)¶ Test whether
x
is numerically equal to some integer
-
real_valued
(x)¶ Test whether
x
is 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
.
Integers¶
-
count_ones
(x::Integer) → Integer¶ Number of ones in the binary representation of
x
.Example:
count_ones(7) -> 3
-
count_zeros
(x::Integer) → Integer¶ Number of zeros in the binary representation of
x
.Example:
count_zeros(int32(2 ^ 16 - 1)) -> 16
-
leading_zeros
(x::Integer) → Integer¶ Number of zeros leading the binary representation of
x
.Example:
leading_zeros(int32(1)) -> 31
-
leading_ones
(x::Integer) → Integer¶ Number of ones leading the binary representation of
x
.Example:
leading_ones(int32(2 ^ 32 - 2)) -> 31
-
trailing_zeros
(x::Integer) → Integer¶ Number of zeros trailing the binary representation of
x
.Example:
trailing_zeros(2) -> 1
-
trailing_ones
(x::Integer) → Integer¶ Number of ones trailing the binary representation of
x
.Example:
trailing_ones(3) -> 2
-
isprime
(x::Integer) → Bool¶ Returns
true
ifx
is prime, andfalse
otherwise.Example:
isprime(3) -> true
-
isodd
(x::Integer) → Bool¶ Returns
true
ifx
is odd (that is, not divisible by 2), andfalse
otherwise.Example:
isodd(9) -> false
-
iseven
(x::Integer) → Bool¶ Returns
true
isx
is even (that is, divisible by 2), andfalse
otherwise.Example:
iseven(1) -> false
Random Numbers¶
Random number generateion 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
()¶ 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
(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.
Arrays¶
Basic functions¶
-
ndims
(A) → Integer¶ Returns the number of dimensions of A
-
size
(A)¶ Returns a tuple containing the dimensions of A
-
eltype
(A) Returns the type of the elements contained in A
-
length
(A) → Integer Returns the number of elements in A (note that this differs from MATLAB where
length(A)
is the largest dimension ofA
)
-
nnz
(A)¶ Counts the number of nonzero values in array A (dense or sparse)
-
scale!
(A, k)¶ Scale the contents of an array A with k (in-place)
-
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 Bool array with all values set to true
-
falses
(dims)¶ Create a Bool array 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)¶ Construct 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
-
linspace
(start, stop, n)¶ Construct a vector of
n
linearly-spaced elements fromstart
tostop
.
-
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
-
bsxfun
(fn, A, B[, C...])¶ Apply binary function
fn
to two or more arrays, with singleton dimensions expanded.
Indexing, Assignment, and Concatenation¶
-
getindex
(A, ind) Returns a subset of array
A
as specified byind
, which may be anInt
, aRange
, or aVector
.
-
sub
(A, ind)¶ Returns a SubArray, which stores the input
A
andind
rather than computing the result immediately. Callinggetindex
on a SubArray computes the indices on the fly.
-
slicedim
(A, d, i)¶ Return all the data of
A
where the index for dimensiond
equalsi
. Equivalent toA[:,:,...,i,:,:,...]
wherei
is in positiond
.
-
setindex!
(A, X, ind) Store values from array
X
within some subset ofA
as specified byind
.
-
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)
.
-
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
.
-
findn
(A)¶ Return a vector of indexes for each dimension giving the locations of the non-zeros in
A
.
-
nonzeros
(A)¶ Return a vector of the non-zero values in array
A
.
-
findfirst
(A)¶ Return the index of the first non-zero value in
A
.
-
findfirst
(A, v) Return the index of the first element equal to
v
inA
.
-
findfirst
(predicate, A) Return the index of the first element that satisfies the given predicate in
A
.
-
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 topermute(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.
Array functions¶
-
cumprod
(A[, dim])¶ Cumulative product along a dimension.
-
cumsum
(A[, dim])¶ Cumulative sum along a dimension.
-
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.
-
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.
-
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.
Combinatorics¶
-
nthperm
(v, k)¶ Compute the kth lexicographic permutation of a vector.
-
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)¶ Randomly rearrange the elements of a vector.
-
shuffle!
(v)¶ In-place version of
shuffle()
.
-
reverse
(v)¶ Reverse vector
v
.
-
reverse!
(v) → v¶ In-place version of
reverse()
.
-
combinations
(array, n)¶ Generate all combinations of
n
elements from a given array. Because the number of combinations can be very large, this function runs inside a Task to produce values on demand. Writec = @task combinations(a,n)
, then iteratec
or callconsume
on it.
-
integer_partitions
(n, m)¶ Generate all arrays of
m
integers that sum ton
. Because the number of partitions can be very large, this function runs inside a Task to produce values on demand. Writec = @task integer_partitions(n,m)
, then iteratec
or callconsume
on it.
-
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 runs inside a Task to produce values on demand. Write
c = @task partitions(a)
, then iteratec
or callconsume
on it.
Statistics¶
-
mean
(v[, region])¶ Compute the mean of whole array
v
, or optionally along the dimensions inregion
.
-
std
(v[, region])¶ Compute the sample standard deviation of a vector or array``v``, optionally along dimensions in
region
. The algorithm returns an estimator of the generative distribution’s standard deviation under the assumption that each entry ofv
is an IID draw from that generative distribution. This computation is equivalent to calculatingsqrt(sum((v - mean(v)).^2) / (length(v) - 1))
.
-
stdm
(v, m)¶ Compute the sample standard deviation of a vector
v
with known meanm
.
-
var
(v[, region])¶ Compute the sample variance of a vector or array``v``, optionally along dimensions in
region
. The algorithm will return an estimator of the generative distribution’s variance under the assumption that each entry ofv
is an IID draw from that generative distribution. This computation is equivalent to calculatingsum((v - mean(v)).^2) / (length(v) - 1)
.
-
varm
(v, m)¶ Compute the sample variance of a vector
v
with known meanm
.
-
median
(v)¶ Compute the median of a vector
v
.
-
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.
-
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
, with thei``th element being ``sum(e[i] .< v .<= e[i+1])
.
-
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.
-
midpoints
(e)¶ Compute the midpoints of the bins with edges
e
. The result is a vector/range of lengthlength(e) - 1
.
-
quantile
(v, p)¶ Compute the quantiles of a vector
v
at a specified set of probability valuesp
.
-
quantile
(v) Compute the quantiles of a vector
v
at the probability values[.0, .2, .4, .6, .8, 1.0]
.
-
cov
(v1[, v2])¶ Compute the Pearson covariance between two vectors
v1
andv2
. If called with a single elementv
, then computes covariance of columns ofv
.
-
cor
(v1[, v2])¶ Compute the Pearson correlation between two vectors
v1
andv2
. If called with a single elementv
, then computes correlation of columns ofv
.
Signal Processing¶
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}[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 backward FFT computes \(\operatorname{BDFT}[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 backward FFT simply performs this operation along each transformed dimension of
A
. The inverse FFT computes the same thing divided by the product of the transformed dimensions.
-
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.)
-
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_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
.
-
FFTW.
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
FFTW.plan_r2r()
to pre-plan optimized r2r transforms.
-
FFTW.
r2r!
(A, kind[, dims])¶ FFTW.r2r!()
is the same asFFTW.r2r()
, but operates in-place onA
, which must be an array of real or complex floating-point numbers.
-
FFTW.
plan_r2r
(A, kind[, dims[, flags[, timelimit]]])¶ Pre-plan an optimized r2r transform, similar to
plan_fft()
except that the transforms (and the first three arguments) correspond toFFTW.r2r()
andFFTW.r2r!()
, respectively.
-
FFTW.
plan_r2r!
(A, kind[, dims[, flags[, timelimit]]])¶ Similar to
plan_fft()
, but corresponds toFFTW.r2r!()
.
-
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)¶ Apply filter described by vectors
a
andb
to vectorx
.
-
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.
-
xcorr
(u, v)¶ Compute the cross-correlation of two vectors.
Parallel Computing¶
-
addprocs_local
(n)¶ Add processes on the local machine. Can be used to take advantage of multiple cores.
-
addprocs_ssh
({"host1", "host2", ...})¶ 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.
-
addprocs_sge
(n)¶ Add processes via the Sun/Oracle Grid Engine batch queue, using
qsub
.
-
nprocs
()¶ Get the number of available processors.
-
myid
()¶ Get the id of the current processor.
-
pmap
(f, c)¶ Transform collection
c
by applyingf
to each element in parallel.
-
remote_call
(id, func, args...)¶ Call a function asynchronously on the given arguments on the specified processor. Returns a
RemoteRef
.
-
wait
(RemoteRef)¶ Wait for a value to become available for the specified remote reference.
-
fetch
(RemoteRef)¶ Wait for and get the value of a remote reference.
-
remote_call_wait
(id, func, args...)¶ Perform
wait(remote_call(...))
in one message.
-
remote_call_fetch
(id, func, args...)¶ Perform
fetch(remote_call(...))
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
.
-
take
(RemoteRef)¶ Fetch the value of a remote reference, removing it so that the reference is empty again.
-
RemoteRef
()¶ Make an uninitialized remote reference on the local machine.
-
RemoteRef
(n) Make an uninitialized remote reference on processor
n
.
Distributed Arrays¶
-
DArray
(init, dims[, procs, dist])¶ Construct a distributed array.
init
is a function accepting a tuple of index ranges. This function should return a chunk of the distributed array for the specified indexes.dims
is the overall size of the distributed array.procs
optionally specifies a vector of processor IDs to use.dist
is an integer vector specifying how many chunks the distributed array should be divided into in each dimension.
-
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
-
localize
(d)¶ Get the local piece of a distributed array
-
myindexes
(d)¶ A tuple describing the indexes owned by the local processor
-
procs
(d)¶ Get the vector of processors 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.
-
success
(command)¶ Run a command object, constructed with backticks, and tell whether it was successful (exited with a code of 0).
-
readsfrom
(command)¶ Starts running a command asynchronously, and returns a tuple (stream,process). The first value is a stream reading from the process’ standard output.
-
writesto
(command)¶ Starts running a command asynchronously, and returns a tuple (stream,process). The first value is a stream writing to the process’ standard input.
-
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.
-
>
() Redirect standard output of a process.
Example:
run(`ls` > "out.log")
-
<
() Redirect standard input of a process.
-
>>
() Redirect standard output of a process, appending to the destination file.
-
.>
() 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. Returns the new current 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.
-
rmdir
(path)¶ Remove the directory named
path
.
-
getpid
() → Int32¶ Get julia’s process ID.
-
time
()¶ Get the system time in seconds since the epoch, with fairly high (typically, microsecond) resolution.
-
time_ns
()¶ Get the time in nanoseconds. The time corresponding to 0 is undefined, and wraps every 5.8 years.
-
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()
.
-
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.
C Interface¶
-
ccall
((symbol, library) or fptr, RetType, (ArgType1, ...), ArgVar1, ...)¶ Call function in C-exported shared library, specified by (function name, library) tuple (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.
-
cfunction
(fun::Function, RetType::Type, (ArgTypes...))¶ Generate C-callable function pointer from Julia function.
-
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, and RTLD_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 is RTLD_LAZY|RTLD_DEEPBIND|RTLD_LOCAL. An important usage of these flags, on POSIX platforms, is to specify RTLD_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.
-
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.
-
c_free
(addr::Ptr)¶ Call free() from C standard library.
-
unsafe_ref
(p::Ptr{T}, i::Integer)¶ Dereference the pointer
p[i]
or*p
, returning a copy of type T.
-
unsafe_assign
(p::Ptr{T}, x, i::Integer)¶ Assign to the pointer
p[i] = x
or*p = x
, making a copy of object x into the memory at p.
-
pointer
(a[, index])¶ Get the native address of an array 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.
Errors¶
-
error
(message::String)¶ Raise an error with the given message
-
throw
(e)¶ Throw an object as an exception
-
errno
()¶ Get the value of the C library’s
errno
-
strerror
(n)¶ Convert a system call error code to a descriptive string
-
assert
(cond)¶ Raise an error if
cond
is false. Also available as the macro@assert expr
.
Tasks¶
-
Task
(func)¶ Create a
Task
(i.e. thread, or coroutine) to execute the given function. 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
args
. On subsequent switches,args
are returned from the task’s last call toyieldto
.
-
current_task
()¶ Get the currently running Task.
-
istaskdone
(task)¶ Tell whether a task has exited.
-
consume
(task)¶ Receive the next value passed to
produce
by the specified task.
-
produce
(value)¶ Send the given value to the last
consume
call, switching to the consumer task.
-
make_scheduled
(task)¶ Register a task with the main event loop, so it will automatically run when possible.
-
yield
()¶ For scheduled tasks, switch back to the scheduler to allow another scheduled task to run.
-
tls
(symbol)¶ Look up the value of a symbol in the current task’s task-local storage.
-
tls
(symbol, value) Assign a value to a symbol in the current task’s task-local storage.