diff --git a/doc/manual/arrays.rst b/doc/manual/arrays.rst index 93891549a9eba..fb37a729a3c6e 100644 --- a/doc/manual/arrays.rst +++ b/doc/manual/arrays.rst @@ -32,18 +32,24 @@ Julia array library ensures that inputs are not modified by library functions. User code, if it needs to exhibit similar behaviour, should take care to create a copy of inputs that it may modify. +Arrays +====== + Basic Functions --------------- -1. ``ndims(A)`` — the number of dimensions of A -2. ``size(A,n)`` — the size of A in a particular dimension -3. ``size(A)`` — a tuple containing the dimensions of A -4. ``eltype(A)`` — the type of the elements contained in A -5. ``length(A)`` — the number of elements in A -6. ``nnz(A)`` — the number of nonzero values in A -7. ``stride(A,k)`` — the size of the stride along dimension k -8. ``strides(A)`` — a tuple of the linear index distances between - adjacent elements in each dimension +=============== ============================================================================== +Function Description +=============== ============================================================================== +``eltype(A)`` the type of the elements contained in A +``length(A)`` the number of elements in A +``ndims(A)`` the number of dimensions of A +``nnz(A)`` the number of nonzero values in A +``size(A)`` a tuple containing the dimensions of A +``size(A,n)`` the size of A in a particular dimension +``stride(A,k)`` the stride (linear index distance between adjacent elements) along dimension k +``strides(A)`` a tuple of the strides in each dimension +=============== ============================================================================== Construction and Initialization ------------------------------- @@ -53,41 +59,38 @@ the following list of such functions, calls with a ``dims...`` argument can either take a single tuple of dimension sizes or a series of dimension sizes passed as a variable number of arguments. -1. ``Array(type, dims...)`` — an uninitialized dense array -2. ``cell(dims...)`` — an uninitialized cell array (heterogeneous - array) -3. ``zeros(type, dims...)`` — an array of all zeros of specified type -4. ``ones(type, dims...)`` — an array of all ones of specified type -5. ``trues(dims...)`` — a ``Bool`` array with all values ``true`` -6. ``falses(dims...)`` — a ``Bool`` array with all values ``false`` -7. ``reshape(A, dims...)`` — an array with the same data as the given - array, but with different dimensions. -8. ``copy(A)`` — copy ``A`` -9. ``deepcopy(A)`` — copy ``A``, recursively copying its elements -10. ``similar(A, element_type, dims...)`` — an uninitialized array of - the same type as the given array (dense, sparse, etc.), but with the - specified element type and dimensions. The second and third - arguments are both optional, defaulting to the element type and - dimensions of ``A`` if omitted. -11. ``reinterpret(type, A)`` — an array with the same binary data as the - given array, but with the specified element type. -12. ``rand(dims)`` — random array with ``Float64`` uniformly distributed - values in [0,1) -13. ``randf(dims)`` — random array with ``Float32`` uniformly - distributed values in [0,1) -14. ``randn(dims)`` — random array with ``Float64`` normally distributed - random values with a mean of 0 and standard deviation of 1 -15. ``eye(n)`` — n-by-n identity matrix -16. ``eye(m, n)`` — m-by-n identity matrix -17. ``linspace(start, stop, n)`` — a vector of ``n`` linearly-spaced - elements from ``start`` to ``stop``. -18. ``fill!(A, x)`` — fill the array ``A`` with value ``x`` - -The last function, ``fill!``, is different in that it modifies an -existing array instead of constructing a new one. As a convention, -functions with this property have names ending with an exclamation -point. These functions are sometimes called "mutating" functions, or -"in-place" functions. +===================================== ===================================================================== +Function Description +===================================== ===================================================================== +``Array(type, dims...)`` an uninitialized dense array +``cell(dims...)`` an uninitialized cell array (heterogeneous array) +``zeros(type, dims...)`` an array of all zeros of specified type +``ones(type, dims...)`` an array of all ones of specified type +``trues(dims...)`` a ``Bool`` array with all values ``true`` +``falses(dims...)`` a ``Bool`` array with all values ``false`` +``reshape(A, dims...)`` an array with the same data as the given array, but with + different dimensions. +``copy(A)`` copy ``A`` +``deepcopy(A)`` copy ``A``, recursively copying its elements +``similar(A, element_type, dims...)`` an uninitialized array of the same type as the given array + (dense, sparse, etc.), but with the specified element type and + dimensions. The second and third arguments are both optional, + defaulting to the element type and dimensions of ``A`` if omitted. +``reinterpret(type, A)`` an array with the same binary data as the given array, but with the + specified element type +``rand(dims)`` ``Array`` of ``Float64``\ s with random, iid[#]_ and uniformly + distributed values in [0,1) +``randf(dims)`` ``Array`` of ``Float32``\ s with random, iid and uniformly + distributed values in [0,1) +``randn(dims)`` ``Array`` of ``Float64``\ s with random, iid and standard normally + distributed random values +``eye(n)`` ``n``-by-``n`` identity matrix +``eye(m, n)`` ``m``-by-``n`` identity matrix +``linspace(start, stop, n)`` vector of ``n`` linearly-spaced elements from ``start`` to ``stop`` +``fill!(A, x)`` fill the array ``A`` with value ``x`` +===================================== ===================================================================== + +.. [#] *iid*, independently and identically distributed. Comprehensions -------------- @@ -108,9 +111,7 @@ ranges ``rx``, ``ry``, etc. and each ``F(x,y,...)`` evaluation returns a scalar. The following example computes a weighted average of the current element -and its left and right neighbour along a 1-d grid. - -:: +and its left and right neighbor along a 1-d grid. :: julia> const x = rand(8) 8-element Float64 Array: @@ -132,9 +133,9 @@ and its left and right neighbour along a 1-d grid. 0.245097 0.241854 -NOTE: In the above example, ``x`` is declared as constant because type -inference in Julia does not work as well on non-constant global -variables. +.. note:: In the above example, ``x`` is declared as constant because type + inference in Julia does not work as well on non-constant global + variables. The resulting array type is inferred from the expression; in order to control the type explicitly, the type can be prepended to the comprehension. For example, @@ -235,46 +236,83 @@ Concatenation ------------- Arrays can be concatenated along any dimension using the following -syntax: +functions: -1. ``cat(dim, A...)`` — concatenate input n-d arrays along the dimension - ``dim`` -2. ``vcat(A...)`` — Shorthand for ``cat(1, A...)`` -3. ``hcat(A...)`` — Shorthand for ``cat(2, A...)`` -4. ``hvcat(A...)`` +================ ====================================================== +Function Description +================ ====================================================== +``cat(k, A...)`` concatenate input n-d arrays along the dimension ``k`` +``vcat(A...)`` shorthand for ``cat(1, A...)`` +``hcat(A...)`` shorthand for ``cat(2, A...)`` +``hvcat(A...)`` +================ ====================================================== Concatenation operators may also be used for concatenating arrays: -1. ``[A B C ...]`` — calls ``hcat`` -2. ``[A, B, C, ...]`` — calls ``vcat`` -3. ``[A B; C D; ...]`` — calls ``hvcat`` +=================== ========= +Expression Calls +=================== ========= +``[A B C ...]`` ``hcat`` +``[A, B, C, ...]`` ``vcat`` +``[A B; C D; ...]`` ``hvcat`` +=================== ========= Vectorized Operators and Functions ---------------------------------- -The following operators are supported for arrays. In case of binary -operators, the dot version of the operator should be used when both -inputs are non-scalar, and any version of the operator may be used if -one of the inputs is a scalar. +The following operators are supported for arrays. In case of binary operators, +the dot (element-wise) version of the operator should be used when both inputs +are non-scalar, and any version of the operator may be used if one of the +inputs is a scalar. -1. Unary Arithmetic — ``-`` -2. Binary Arithmetic — ``+``, ``-``, ``*``, ``.*``, ``/``, ``./``, +1. Unary arithmetic — ``-``, ``+``, ``!`` +2. Binary arithmetic — ``+``, ``-``, ``*``, ``.*``, ``/``, ``./``, ``\``, ``.\``, ``^``, ``.^``, ``div``, ``mod`` 3. Comparison — ``==``, ``!=``, ``<``, ``<=``, ``>``, ``>=`` -4. Unary Boolean or Bitwise — ``~`` -5. Binary Boolean or Bitwise — ``&``, ``|``, ``$`` -6. Trigonometrical functions — ``sin``, ``cos``, ``tan``, ``sinh``, - ``cosh``, ``tanh``, ``asin``, ``acos``, ``atan``, ``atan2``, - ``sec``, ``csc``, ``cot``, ``asec``, ``acsc``, ``acot``, ``sech``, - ``csch``, ``coth``, ``asech``, ``acsch``, ``acoth``, ``sinc``, - ``cosc``, ``hypot`` -7. Logarithmic functions — ``log``, ``log2``, ``log10``, ``log1p`` -8. Exponential functions — ``exp``, ``expm1``, ``exp2``, ``ldexp`` -9. Rounding functions — ``ceil``, ``floor``, ``trunc``, ``round``, - ``ipart``, ``fpart`` -10. Other mathematical functions — ``min``, ``max,`` ``abs``, ``pow``, - ``sqrt``, ``cbrt``, ``erf``, ``erfc``, ``gamma``, ``lgamma``, - ``real``, ``conj``, ``clamp`` +4. Unary Boolean or bitwise — ``~`` +5. Binary Boolean or bitwise — ``&``, ``|``, ``$`` + +The following built-in functions are also vectorized, whereby the functions act +element-wise:: + + abs abs2 angle cbrt + airy airyai airyaiprime airybi airybiprime airyprime + acos acosh asin asinh atan atan2 atanh + cos cosh sin sinh tan tanh sinc cosc + besselh besseli besselj besselj0 besselj1 besselk bessely bessely0 bessely1 + exp erf erfc exp2 expm1 + beta dawson digamma erfcx erfi + exponent eta zeta gamma + hankelh1 hankelh2 + ceil floor round trunc + iceil ifloor iround itrunc + isfinite isinf isnan + lbeta lfact lgamma + log log10 log1p log2 + copysign max min significand + sqrt hypot + +Furthermore, Julia provides the ``@vectorize_1arg`` and ``@vectorize_2arg`` +macros to automatically vectorize any function of one or two arguments +respectively. Each of these takes two arguments, namely the ``Type`` of +argument (which is usually chosen to be to be the most general possible) and +the name of the function to vectorize. Here is a simple example:: + + julia> square(x) = x^2 + # methods for generic function square + square(x) at none:1 + + julia> @vectorize_1arg Number square + # methods for generic function square + square{T<:Number}(x::AbstractArray{T<:Number,1}) at operators.jl:216 + square{T<:Number}(x::AbstractArray{T<:Number,2}) at operators.jl:217 + square{T<:Number}(x::AbstractArray{T<:Number,N}) at operators.jl:219 + square(x) at none:1 + + julia> square([1 2 4; 5 6 7]) + 2x3 Int64 Array: + 1 4 16 + 25 36 49 Broadcasting ------------ @@ -385,130 +423,8 @@ stride parameters. -1.175 -0.786311 0.0 -0.414549 -*********************** - Matrix factorizations -*********************** - -`Matrix factorizations (a.k.a. matrix decompositions) `_ -compute the factorization of a matrix into a product of matrices, and -are one of the central concepts in linear algebra. - -The following table summarizes the types of matrix factorizations that have been -implemented in Julia. Details of their associated methods can be found -in the :ref:`stdlib-linalg` section of the standard library documentation. - -=================== =========== -``Cholesky`` `Cholesky factorization `_ -``CholeskyPivoted`` `Pivoted `_ Cholesky factorization -``LU`` `LU factorization `_ -``QRPivoted`` Pivoted `QR factorization `_ -``Hessenberg`` `Hessenberg decomposition `_ -``Eigen`` `Spectral decomposition `_ -``SVD`` `Singular value decomposition `_ -``GeneralizedSVD`` `Generalized SVD `_ -=================== =========== - -Special matrices ----------------- - -`Matrices with special symmetries and structures `_ -arise often in linear algebra and are frequently associated with -various matrix factorizations. -Julia features a rich collection of special matrix types, which allow for fast -computation with specialized routines that are specially developed for -particular matrix types. - -The following tables summarize the types of special matrices that have been -implemented in Julia, as well as whether hooks to various optimized methods -for them in LAPACK are available. - -+--------------------+-----------------------------------------------------------------------------------+ -| ``Hermitian`` | `Hermitian matrix `_ | -+--------------------+-----------------------------------------------------------------------------------+ -| ``Triangular`` | Upper/lower `triangular matrix `_ | -+--------------------+-----------------------------------------------------------------------------------+ -| ``Tridiagonal`` | `Tridiagonal matrix `_ | -+--------------------+-----------------------------------------------------------------------------------+ -| ``SymTridiagonal`` | Symmetric tridiagonal matrix | -+--------------------+-----------------------------------------------------------------------------------+ -| ``Bidiagonal`` | Upper/lower `bidiagonal matrix `_ | -+--------------------+-----------------------------------------------------------------------------------+ -| ``Diagonal`` | `Diagonal matrix `_ | -+--------------------+-----------------------------------------------------------------------------------+ - - -Elementary operations ---------------------- - -+--------------------+-------+-------+-------+-------+---------------------+ -| Matrix type | ``+`` | ``-`` | ``*`` | ``\`` | Other functions with| -| | | | | | optimized methods | -+--------------------+-------+-------+-------+-------+---------------------+ -| ``Hermitian`` | | | | XY | ``inv``, | -| | | | | | ``sqrtm``, ``expm`` | -+--------------------+-------+-------+-------+-------+---------------------+ -| ``Triangular`` | | | XY | XY | ``inv``, ``det`` | -+--------------------+-------+-------+-------+-------+---------------------+ -| ``SymTridiagonal`` | X | X | XZ | XY | ``eigmax/min`` | -+--------------------+-------+-------+-------+-------+---------------------+ -| ``Tridiagonal`` | X | X | XZ | XY | | -+--------------------+-------+-------+-------+-------+---------------------+ -| ``Bidiagonal`` | X | X | XZ | XY | | -+--------------------+-------+-------+-------+-------+---------------------+ -| ``Diagonal`` | X | X | XY | XY | ``inv``, ``det``, | -| | | | | | ``logdet``, ``/`` | -+--------------------+-------+-------+-------+-------+---------------------+ - -Legend: - -+---+---------------------------------------------------------------+ -| X | An optimized method for matrix-matrix operations is available | -+---+---------------------------------------------------------------+ -| Y | An optimized method for matrix-vector operations is available | -+---+---------------------------------------------------------------+ -| Z | An optimized method for matrix-scalar operations is available | -+---+---------------------------------------------------------------+ - -Matrix factorizations ---------------------- - -+--------------------+-------------------------------------+-----------------------------+ -| Matrix type | Eigensystems | Singular values and vectors | -| +---------+-------------+-------------+---------+-------------------+ -| | ``eig`` | ``eigvals`` | ``eigvecs`` | ``svd`` | ``svdvals`` | -+--------------------+---------+-------------+-------------+---------+-------------------+ -| ``Hermitian`` | | ABC | | | | -| | | | | | | -+--------------------+---------+-------------+-------------+---------+-------------------+ -| ``Triangular`` | | | | | | -+--------------------+---------+-------------+-------------+---------+-------------------+ -| ``SymTridiagonal`` | A | ABC | AD | | | -+--------------------+---------+-------------+-------------+---------+-------------------+ -| ``Tridiagonal`` | | | | | | -+--------------------+---------+-------------+-------------+---------+-------------------+ -| ``Bidiagonal`` | | | | A | A | -+--------------------+---------+-------------+-------------+---------+-------------------+ -| ``Diagonal`` | | A | | | | -| | | | | | | -+--------------------+---------+-------------+-------------+---------+-------------------+ - -Legend: - -+---+-----------------------------------------------------------------------------------------------------------------------------------+------------------------+ -| A | An optimized method to find all the characteristic values and/or vectors is available | e.g. ``eigvals(M)`` | -+---+-----------------------------------------------------------------------------------------------------------------------------------+------------------------+ -| B | An optimized method to find the ``il``:sup:`th` through the ``ih``:sup:`th` characteristic values are available | ``eigvals(M, il, ih)`` | -+---+-----------------------------------------------------------------------------------------------------------------------------------+------------------------+ -| C | An optimized method to find the characteristic values in the interval [``vl``, ``vh``] is available | ``eigvals(M, vl, vh)`` | -+---+-----------------------------------------------------------------------------------------------------------------------------------+------------------------+ -| D | An optimized method to find the characteristic vectors corresponding to the characteristic values ``x=[x1, x2,...]`` is available | ``eigvecs(M, x)`` | -+---+-----------------------------------------------------------------------------------------------------------------------------------+------------------------+ - - - -****************** - Sparse Matrices -****************** +Sparse Matrices +=============== `Sparse matrices `_ are matrices that contain enough zeros that storing them in a special data diff --git a/doc/manual/complex-and-rational-numbers.rst b/doc/manual/complex-and-rational-numbers.rst index 14371eda7e9d6..6de1c7528a136 100644 --- a/doc/manual/complex-and-rational-numbers.rst +++ b/doc/manual/complex-and-rational-numbers.rst @@ -5,9 +5,9 @@ ****************************** Julia ships with predefined types representing both complex and rational -numbers, and supports all the mathematical operations discussed in -:ref:`man-mathematical-operations` on them. -Promotions are defined so that operations on any combination of +numbers, and supports all :ref:`standard mathematical operations +` on them. :ref:`man-promotions` +are defined so that operations on any combination of predefined numeric types, whether primitive or composite, behave as expected. @@ -20,8 +20,8 @@ The global constant ``im`` is bound to the complex number *i*, representing the principal square root of -1. It was deemed harmful to co-opt the name ``i`` for a global constant, since it is such a popular index variable name. Since Julia allows numeric literals to be -:ref:`juxtaposed with identifiers as -coefficients `, +:ref:`juxtaposed with identifiers as coefficients +`, this binding suffices to provide convenient syntax for complex numbers, similar to the traditional mathematical notation:: @@ -144,23 +144,23 @@ versus ``-1 + 0im`` even though ``-1 == -1 + 0im``:: julia> sqrt(-1 + 0im) 0.0 + 1.0im -If you need to construct a complex number using variables, the literal -numeric coefficient notation will not work, although explicitly writing -the multiplication operation will:: +The :ref:`literal numeric coefficient notation ` +does work when constructing complex number from variables. Instead, the +multiplication must be explicitly written out:: julia> a = 1; b = 2; a + b*im 1 + 2im -Constructing complex numbers from variable values like this, however, -is not recommended. Use the ``complex`` function to construct a -complex value directly from its real and imaginary parts instead. This -construction is preferred for variable arguments because it is more -efficient than the multiplication and addition construct, but also -because certain values of ``b`` can yield unexpected results:: +Hoever, this is *not* recommended; Use the ``complex`` function instead to +construct a complex value directly from its real and imaginary parts.:: julia> complex(a,b) 1 + 2im +This construction avoids the multiplication and addition operations, and also +sidesteps unexpected results that can arise with the former for certain values +of ``b``. + ``Inf`` and ``NaN`` propagate through complex numbers in the real and imaginary parts of a complex number as described in the :ref:`man-special-floats` section:: @@ -260,7 +260,7 @@ Constructing infinite rational values is acceptable:: julia> typeof(ans) Rational{Int64} -Trying to construct a NaN rational value, however, is not:: +Trying to construct a ``NaN`` rational value, however, is not:: julia> 0//0 invalid rational: 0//0 diff --git a/doc/manual/constructors.rst b/doc/manual/constructors.rst index ad281013424b1..b39b8961cb489 100644 --- a/doc/manual/constructors.rst +++ b/doc/manual/constructors.rst @@ -4,7 +4,7 @@ Constructors ************** -Constructors are functions that create new objects — specifically, +Constructors [#]_ are functions that create new objects — specifically, instances of :ref:`man-composite-types`. In Julia, type objects also serve as constructor functions: they create new instances of themselves when applied to an argument tuple as a function. @@ -39,6 +39,15 @@ construct objects with fewer or different types of parameters than they have fields. Julia's system for object construction addresses all of these cases and more. +.. [#] Nomenclature: while the term “constructor” generally refers to + the entire function which constructs objects of a type, it is common to + abuse terminology slightly and refer to specific constructor methods as + “constructors”. In such situations, it is generally clear from context + that the term is used to mean “constructor method” rather than + “constructor function”, especially as it is often used in the sense of + singling out a particular method of the constructor from all of the + others. + Outer Constructor Methods ------------------------- @@ -71,23 +80,6 @@ this are called *outer* constructor methods. Outer constructor methods can only ever create a new instance by calling another constructor method, such as the automatically provided default one. -.. raw:: html - - - Inner Constructor Methods ------------------------- @@ -178,11 +170,9 @@ with an explicit constructor:: julia> T1(1.0) no method T1(Float64,) - in method_missing at /Users/stefan/projects/julia/base/base.jl:58 julia> T2(1.0) no method T2(Float64,) - in method_missing at /Users/stefan/projects/julia/base/base.jl:58 It is considered good form to provide as few inner constructor methods as possible: only those taking all arguments explicitly and enforcing @@ -307,7 +297,6 @@ types of the arguments given to the constructor. Here are some examples:: julia> Point(1,2.5) no method Point(Int64,Float64) - in method_missing at /Users/stefan/projects/julia/base/base.jl:58 ## explicit T ## @@ -316,14 +305,12 @@ types of the arguments given to the constructor. Here are some examples:: julia> Point{Int64}(1.0,2.5) no method Point(Float64,Float64) - in method_missing at /Users/stefan/projects/julia/base/base.jl:58 julia> Point{Float64}(1.0,2.5) Point(1.0,2.5) julia> Point{Float64}(1,2) no method Point(Int64,Int64) - in method_missing at /Users/stefan/projects/julia/base/base.jl:58 As you can see, for constructor calls with explicit type parameters, the arguments must match that specific type: ``Point{Int64}(1,2)`` works, diff --git a/doc/manual/control-flow.rst b/doc/manual/control-flow.rst index 6c4d308d24e5e..9f05039c69d37 100644 --- a/doc/manual/control-flow.rst +++ b/doc/manual/control-flow.rst @@ -80,10 +80,9 @@ anatomy of the ``if``-``elseif``-``else`` conditional syntax:: println("x is equal to y") end -The semantics are just what you'd expect: if the condition expression -``x < y`` is ``true``, then the corresponding block is evaluated; -otherwise the condition expression ``x > y`` is evaluated, and if it is -``true``, the corresponding block is evaluated; if neither expression is +If the condition expression ``x < y`` is ``true``, then the corresponding block +is evaluated; otherwise the condition expression ``x > y`` is evaluated, and if +it is ``true``, the corresponding block is evaluated; if neither expression is true, the ``else`` block is evaluated. Here it is in action:: julia> function test(x, y) @@ -252,9 +251,8 @@ this behavior:: You can easily experiment in the same way with the associativity and precedence of various combinations of ``&&`` and ``||`` operators. -If you want to perform boolean operations *without* short-circuit -evaluation behavior, you can use the bitwise boolean operators -introduced in :ref:`man-mathematical-operations`: +Boolean operations *without* short-circuit evaluation can be done with the +bitwise boolean operators introduced in :ref:`man-mathematical-operations`: ``&`` and ``|``. These are normal functions, which happen to support infix operator syntax, but always evaluate their arguments:: @@ -440,13 +438,73 @@ diagnostic error message, or if the programmer has provided code to handle such exceptional circumstances, allow that code to take the appropriate action. -The ``error`` function is used to indicate that an unexpected condition -has occurred which should interrupt the normal flow of control. The -built in ``sqrt`` function returns ``DomainError()`` if applied to a negative real -value:: +Built-in ``Exception``\ s +~~~~~~~~~~~~~~~~~~~~~~~~~ + +``Exception``\ s are thrown when an unexpected condition has occurred. The +built-in ``Exception``\ s listed below all interrupt the normal flow of control. + +====================== +``Exception`` +---------------------- +``ArgumentError`` +``BoundsError`` +``DivideError`` +``DomainError`` +``EOFError`` +``ErrorException`` +``InexactError`` +``InterruptException`` +``KeyError`` +``LoadError`` +``MemoryError`` +``MethodError`` +``OverflowError`` +``ParseError`` +``SystemError`` +``TypeError`` +``UndefRefError`` +====================== + +For example, the ``sqrt`` function returns a ``DomainError()`` if applied to a +negative real value:: julia> sqrt(-1) - DomainError() + ERROR: DomainError() + in sqrt at math.jl:117 + +The ``throw`` function +~~~~~~~~~~~~~~~~~~~~~~ + +Exceptions can be created explicitly with ``throw``. For example, a function +defined only for nonnegative numbers could be written to ``throw`` a ``DomainError`` +if the argument is negative. :: + + julia> f(x) = x>=0 ? exp(-x) : throw(DomainError()) + # methods for generic function f + f(x) at none:1 + + julia> f(1) + 0.36787944117144233 + + julia> f(-1) + ERROR: DomainError() + in f at none:1 + +Note that the ``DomainError`` should be called with the parentheses lest the +throw statement return something other than an exception. :: + + julia> typeof(DomainError()) <: Exception + true + + julia> typeof(DomainError) <: Exception + false + +Errors +~~~~~~ + +The ``error`` function is used to produce an ``ErrorException`` that +interrupts the normal flow of control. Suppose we want to stop execution immediately if the square root of a negative number is taken. To do this, we can define a fussy version of @@ -481,61 +539,80 @@ session:: before fussy_sqrt negative x not allowed -Now suppose we want to handle this circumstance rather than just giving -up with an error. To catch an error, you use the ``try`` and ``catch`` -keywords. Here is a rather contrived example that computes the square -root of the absolute value of ``x`` by handling the error raised by -``fussy_sqrt``:: - - function sqrt_abs(x) - try - fussy_sqrt(x) - catch - fussy_sqrt(-x) - end - end +Warnings and informational messages +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - julia> sqrt_abs(2) - 1.4142135623730951 - - julia> sqrt_abs(-2) - 1.4142135623730951 +Julia also provides other functions that write messages to the standard error +I/O, but do not throw any ``Exception``\ s and hence do not interrupt +execution.:: -Of course, it would be far simpler and more efficient to just return -``sqrt(abs(x))``. However, this demonstrates how ``try`` and ``catch`` -operate: the ``try`` block is executed initially, and the value of the -entire construct is the value of the last expression if no exceptions -are thrown during execution; if an exception is thrown during the -evaluation of the ``try`` block, however, execution of the ``try`` code -ceases immediately and the ``catch`` block is evaluated instead. If the -``catch`` block succeeds without incident (it can in turn raise an -exception, which would unwind the call stack further), the value of the -entire ``try``-``catch`` construct is that of the last expression in the -``catch`` block. - -Throw versus Error -~~~~~~~~~~~~~~~~~~ - -The ``error`` function is convenient for indicating that an error has -occurred, but it is built on a more fundamental function: ``throw``. -Perhaps ``throw`` should be introduced first, but typical usage calls -for ``error``, so we have deferred the introduction of ``throw``. Above, -we use a form of the ``try``-``catch`` expression in which no value is -captured by the ``catch`` block, but there is another form:: - - try - # execute some code - catch x - # do something with x - end + julia> info("Hi"); 1+1 + MESSAGE: Hi + 2 + + julia> warn("Hi"); 1+1 + WARNING: Hi + 2 + + julia> error("Hi"); 1+1 + ERROR: Hi + in error at error.jl:21 + +The ``try/catch`` statement +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The ``try/catch`` statement allows for ``Exception``\ s to be tested for. For +example, a customized square root function can be written to automatically +call either the real or complex square root method on demand using +``Exception`` \s :: + + julia> f(x) = try + sqrt(x) + catch + sqrt(complex(x, 0)) + end + # methods for generic function f + f(x) at none:1 + + julia> f(1) + 1.0 + + julia> f(-1) + 0.0 + 1.0im + +``try/catch`` statements also allow the ``Exception`` to be saved in a +variable. In this contrived example, the following example calculates the +square root of the second element of ``x`` if ``x`` is indexable, otherwise +assumes ``x`` is a real number and returns its square root:: + + julia> sqrt_second(x) = try + sqrt(x[2]) + catch y + if y == DomainError() + sqrt(complex(x[2], 0)) + elseif y == BoundsError() + sqrt(x) + end + end -In this form, if the built-in ``throw`` function is called by the -"execute some code" expression, or any callee thereof, the catch block -is executed with the argument of the ``throw`` function bound to the -variable ``x``. The ``error`` function is simply a convenience which -always throws an instance of the type ``ErrorException``. Here we can -see that the object thrown when a divide-by-zero error occurs is of type -``DivideByZeroError``:: + # methods for generic function sqrt_second + sqrt_second(x) at none:1 + + julia> sqrt_second([1 4]) + 2.0 + + julia> sqrt_second([1 -4]) + 0.0 + 2.0im + + julia> sqrt_second(9) + 3.0 + + julia> sqrt_second(-9) + ERROR: DomainError() + in sqrt at math.jl:117 + in sqrt_second at none:7 + +This next example, shows an example when ``DivideByZeroError`` is thrown:: julia> div(1,0) error: integer divide by zero @@ -552,35 +629,22 @@ indicate that an integer division by zero has occurred. Floating-point functions, on the other hand, can simply return ``NaN`` rather than throwing an exception. -Unlike ``error``, which should only be used to indicate an unexpected -condition, ``throw`` is merely a control construct, and can be used to -pass any value back to an enclosing ``try``-``catch``:: - - julia> try - throw("Hello, world.") - catch x - println(x) - end - Hello, world. - -This example is contrived, of course — the power of the -``try``-``catch`` construct lies in the ability to unwind a deeply -nested computation immediately to a much higher level in the stack of -calling functions. There are situations where no error has occurred, but -the ability to unwind the stack and pass a value to a higher level is -desirable. These are the circumstances in which ``throw`` should be used -rather than ``error``. +The power of the ``try/catch`` construct lies in the ability to unwind a deeply +nested computation immediately to a much higher level in the stack of calling +functions. There are situations where no error has occurred, but the ability to +unwind the stack and pass a value to a higher level is desirable. Julia +provides the ``rethrow``, ``backtrace`` and ``catch_backtrace`` functions for +more advanced error handling. finally Clauses ~~~~~~~~~~~~~~~ -In code that performs state changes or uses resources like files, there -is typically clean-up work (such as closing files) that needs to be done -when the code is finished. Exceptions potentially complicate this task, -since they can cause a block of code to exit before reaching its -normal end. The ``finally`` keyword solves this problem, by providing -a way to run some code when a given block of code exits, regardless of -how it exits. +In code that performs state changes or uses resources like files, there is +typically clean-up work (such as closing files) that needs to be done when the +code is finished. Exceptions potentially complicate this task, since they can +cause a block of code to exit before reaching its normal end. The ``finally`` +keyword provides a way to run some code when a given block of code exits, +regardless of how it exits. For example, here is how we can guarantee that an opened file is closed:: @@ -615,7 +679,7 @@ resumed, at which point it will pick up right where it left off. At first, this may seem similar to a function call. However there are two key differences. First, switching tasks does not use any space, so any number of task switches can occur without consuming the call stack. -Second, you may switch among tasks in any order, unlike function calls, +Second, switching among tasks can occur in any order, unlike function calls, where the called function must finish executing before control returns to the calling function. diff --git a/doc/manual/conversion-and-promotion.rst b/doc/manual/conversion-and-promotion.rst index 190d98315034e..bc27097778733 100644 --- a/doc/manual/conversion-and-promotion.rst +++ b/doc/manual/conversion-and-promotion.rst @@ -189,6 +189,8 @@ simply converts both numerator and denominator to that floating point type and then divides. To convert to integer, one can use the ``div`` operator for truncated integer division (rounded towards zero). +.. _man-promotion: + Promotion --------- diff --git a/doc/manual/index.rst b/doc/manual/index.rst index 5e74508fac93c..b8ec5ef04b11d 100644 --- a/doc/manual/index.rst +++ b/doc/manual/index.rst @@ -13,6 +13,7 @@ introduction getting-started + variables integers-and-floating-point-numbers mathematical-operations complex-and-rational-numbers @@ -27,6 +28,7 @@ modules metaprogramming arrays + linear-algebra parallel-computing running-external-programs calling-c-and-fortran-code diff --git a/doc/manual/linear-algebra.rst b/doc/manual/linear-algebra.rst new file mode 100644 index 0000000000000..31a8f2d35e18f --- /dev/null +++ b/doc/manual/linear-algebra.rst @@ -0,0 +1,120 @@ +**************** + Linear algebra +**************** + +Matrix factorizations +===================== + +`Matrix factorizations (a.k.a. matrix decompositions) `_ +compute the factorization of a matrix into a product of matrices, and +are one of the central concepts in linear algebra. + +The following table summarizes the types of matrix factorizations that have been +implemented in Julia. Details of their associated methods can be found +in the :ref:`stdlib-linalg` section of the standard library documentation. + +=================== =========== +``Cholesky`` `Cholesky factorization `_ +``CholeskyPivoted`` `Pivoted `_ Cholesky factorization +``LU`` `LU factorization `_ +``QRPivoted`` Pivoted `QR factorization `_ +``Hessenberg`` `Hessenberg decomposition `_ +``Eigen`` `Spectral decomposition `_ +``SVD`` `Singular value decomposition `_ +``GeneralizedSVD`` `Generalized SVD `_ +=================== =========== + +Special matrices +================ + +`Matrices with special symmetries and structures `_ +arise often in linear algebra and are frequently associated with +various matrix factorizations. +Julia features a rich collection of special matrix types, which allow for fast +computation with specialized routines that are specially developed for +particular matrix types. + +The following tables summarize the types of special matrices that have been +implemented in Julia, as well as whether hooks to various optimized methods +for them in LAPACK are available. + ++--------------------+-----------------------------------------------------------------------------------+ +| ``Hermitian`` | `Hermitian matrix `_ | ++--------------------+-----------------------------------------------------------------------------------+ +| ``Triangular`` | Upper/lower `triangular matrix `_ | ++--------------------+-----------------------------------------------------------------------------------+ +| ``Tridiagonal`` | `Tridiagonal matrix `_ | ++--------------------+-----------------------------------------------------------------------------------+ +| ``SymTridiagonal`` | Symmetric tridiagonal matrix | ++--------------------+-----------------------------------------------------------------------------------+ +| ``Bidiagonal`` | Upper/lower `bidiagonal matrix `_ | ++--------------------+-----------------------------------------------------------------------------------+ +| ``Diagonal`` | `Diagonal matrix `_ | ++--------------------+-----------------------------------------------------------------------------------+ + + +Elementary operations +--------------------- + ++--------------------+-------+-------+-------+-------+---------------------+ +| Matrix type | ``+`` | ``-`` | ``*`` | ``\`` | Other functions with| +| | | | | | optimized methods | ++--------------------+-------+-------+-------+-------+---------------------+ +| ``Hermitian`` | | | | XY | ``inv``, | +| | | | | | ``sqrtm``, ``expm`` | ++--------------------+-------+-------+-------+-------+---------------------+ +| ``Triangular`` | | | XY | XY | ``inv``, ``det`` | ++--------------------+-------+-------+-------+-------+---------------------+ +| ``SymTridiagonal`` | X | X | XZ | XY | ``eigmax/min`` | ++--------------------+-------+-------+-------+-------+---------------------+ +| ``Tridiagonal`` | X | X | XZ | XY | | ++--------------------+-------+-------+-------+-------+---------------------+ +| ``Bidiagonal`` | X | X | XZ | XY | | ++--------------------+-------+-------+-------+-------+---------------------+ +| ``Diagonal`` | X | X | XY | XY | ``inv``, ``det``, | +| | | | | | ``logdet``, ``/`` | ++--------------------+-------+-------+-------+-------+---------------------+ + +Legend: + ++---+---------------------------------------------------------------+ +| X | An optimized method for matrix-matrix operations is available | ++---+---------------------------------------------------------------+ +| Y | An optimized method for matrix-vector operations is available | ++---+---------------------------------------------------------------+ +| Z | An optimized method for matrix-scalar operations is available | ++---+---------------------------------------------------------------+ + +Matrix factorizations +--------------------- + ++--------------------+--------+-------------------------------------+-----------------------------+ +| Matrix type | LAPACK | Eigensystems | Singular values and vectors | +| | Name +---------+-------------+-------------+---------+-------------------+ +| | | ``eig`` | ``eigvals`` | ``eigvecs`` | ``svd`` | ``svdvals`` | ++--------------------+--------+-------------------------------------+-----------------------------+ +| ``Hermitian`` | HE | | ABC | | | | ++--------------------+--------+-------------------------------------+-----------------------------+ +| ``Triangular`` | TR | | | | | | ++--------------------+--------+-------------------------------------+-----------------------------+ +| ``SymTridiagonal`` | ST | A | ABC | AD | | | ++--------------------+--------+-------------------------------------+-----------------------------+ +| ``Tridiagonal`` | GT | | | | | | ++--------------------+--------+-------------------------------------+-----------------------------+ +| ``Bidiagonal`` | BD | | | | A | A | ++--------------------+--------+-------------------------------------+-----------------------------+ +| ``Diagonal`` | DI | | A | | | | ++--------------------+--------+-------------------------------------+-----------------------------+ + +Legend: + ++---+-----------------------------------------------------------------------------------------------------------------------------------+------------------------+ +| A | An optimized method to find all the characteristic values and/or vectors is available | e.g. ``eigvals(M)`` | ++---+-----------------------------------------------------------------------------------------------------------------------------------+------------------------+ +| B | An optimized method to find the ``il``:sup:`th` through the ``ih``:sup:`th` characteristic values are available | ``eigvals(M, il, ih)`` | ++---+-----------------------------------------------------------------------------------------------------------------------------------+------------------------+ +| C | An optimized method to find the characteristic values in the interval [``vl``, ``vh``] is available | ``eigvals(M, vl, vh)`` | ++---+-----------------------------------------------------------------------------------------------------------------------------------+------------------------+ +| D | An optimized method to find the characteristic vectors corresponding to the characteristic values ``x=[x1, x2,...]`` is available | ``eigvecs(M, x)`` | ++---+-----------------------------------------------------------------------------------------------------------------------------------+------------------------+ + diff --git a/doc/manual/mathematical-operations.rst b/doc/manual/mathematical-operations.rst index 8171cffdd6c5a..23089a1e1de5a 100644 --- a/doc/manual/mathematical-operations.rst +++ b/doc/manual/mathematical-operations.rst @@ -197,18 +197,33 @@ The last point is potentially surprising and thus worth noting:: julia> NaN > NaN false -For situations where one wants to compare floating-point values so that -``NaN`` equals ``NaN``, such as hash key comparisons, the function -``isequal`` is also provided, which considers ``NaN``\ s to be equal to -each other: :: +and can cause especial headaches with :ref:`Arrays`:: + + julia> [1 NaN] == [1 NaN] + false + +Julia provides additional functions to test numbers for special values, +which can be useful in situations like hash key comparisons:: + +================= ================================== +Function Tests if +================= ================================== +``isequal(x, y)`` ``x`` and ``y`` are equal in value +``isfinite(x)`` ``x`` is a finite number +``isinf(x)`` ``x`` is infinite +``isnan(x)`` ``x`` is not a number +================= ================================== + +``isequal`` considers ``NaN``\ s of the same type to be equal to each other:: julia> isequal(NaN,NaN) true -Alternatively, the ``isnan`` function tests directly for ``NaN``\ s: :: - - julia> isnan(NaN32) + julia> isequal([1 NaN], [1 NaN]) true + + julia> isequal(NaN,NaN32) + false Mixed-type comparisons between signed integers, unsigned integers, and floats can be very tricky. A great deal of care has been taken to ensure diff --git a/doc/manual/metaprogramming.rst b/doc/manual/metaprogramming.rst index 941f9074dd934..f2f3d25bb9832 100644 --- a/doc/manual/metaprogramming.rst +++ b/doc/manual/metaprogramming.rst @@ -100,6 +100,9 @@ quoting form:: +(x,y) end +Symbols +~~~~~~~ + When the argument to ``:`` is just a symbol, a ``Symbol`` object results instead of an ``Expr``:: @@ -111,10 +114,29 @@ instead of an ``Expr``:: In the context of an expression, symbols are used to indicate access to variables, and when an expression is evaluated, a symbol evaluates to -the value bound to that symbol in the appropriate scope (see :ref:`man-variables-and-scoping` for further details). +the value bound to that symbol in the appropriate :ref:`scope +`. + +Sometimes extra parentheses around the argument to ``:`` are needed to avoid +ambiguity in parsing.:: + + julia> :(:) + :(:) + + julia> :(::) + :(::) -Eval and Interpolation -~~~~~~~~~~~~~~~~~~~~~~ +``Symbol``\ s can also be created using the ``symbol`` function, which takes +a character or string as its argument:: + + julia> symbol('\'') + :' + + julia> symbol("'") + :' + +``eval`` and Interpolation +~~~~~~~~~~~~~~~~~~~~~~~~~~ Given an expression object, one can cause Julia to evaluate (execute) it at the *top level* scope — i.e. in effect like loading from a file or @@ -414,6 +436,8 @@ following macro sets ``x`` to zero in the call environment:: This kind of manipulation of variables should be used judiciously, but is occasionally quite handy. +.. _man-non-standard-string-literals2: + Non-Standard String Literals ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/doc/manual/methods.rst b/doc/manual/methods.rst index 83d4a3eeb7d2c..ea049e55a7b99 100644 --- a/doc/manual/methods.rst +++ b/doc/manual/methods.rst @@ -39,10 +39,10 @@ on the types of all of the function's arguments. This is different than traditional object-oriented languages, where dispatch occurs based only on the first argument, which often has a special argument syntax, and is sometimes implied rather than explicitly written as an -argument.\ `1 <#footnote-1>`_\ Using all of a function's arguments to +argument. [#]_ Using all of a function's arguments to choose which method should be invoked, rather than just the first, is -known as `*multiple -dispatch* `_. Multiple +known as `multiple dispatch +`_. Multiple dispatch is particularly useful for mathematical code, where it makes little sense to artificially deem the operations to "belong" to one argument more than any of the others: does the addition operation in @@ -52,20 +52,13 @@ of all of its arguments. Even beyond mathematical operations, however, multiple dispatch ends up being a very powerful and convenient paradigm for structuring and organizing programs. -.. raw:: html +.. [#] In C++ or Java, for example, in a method call like + ``obj.meth(arg1,arg2)``, the object obj "receives" the method call and is + implicitly passed to the method via the ``this`` keyword, rather then as an + explicit method argument. When the current ``this`` object is the receiver of a + method call, it can be omitted altogether, writing just ``meth(arg1,arg2)``, + with this implied as the receiving object. - Defining Methods ---------------- @@ -156,7 +149,7 @@ The ``2x + y`` definition is only used in the first case, while the conversion of function arguments is ever performed: all conversion in Julia is non-magical and completely explicit. :ref:`man-conversion-and-promotion`, however, shows how clever application of sufficiently advanced technology can be indistinguishable -from magic. [#]_ +from magic.[Clarke61]_ For non-numeric values, and for fewer or more than two arguments, the function ``f`` remains undefined, and applying it will still result in a @@ -422,4 +415,5 @@ In particular, they do not participate in method dispatch. Methods are dispatched based only on positional arguments, with named arguments processed after the matching method is identified. -.. [#] Arthur C. Clarke, *Profiles of the Future* (1961): Clarke's Third Law. +.. [Clarke61] Arthur C. Clarke, *Profiles of the Future* (1961): Clarke's Third Law. + diff --git a/doc/manual/parallel-computing.rst b/doc/manual/parallel-computing.rst index d97cd824e3270..a18f545fa1914 100644 --- a/doc/manual/parallel-computing.rst +++ b/doc/manual/parallel-computing.rst @@ -579,6 +579,6 @@ Sending Instructions To All Processors It is often useful to execute a statement on all processors, particularly for setup tasks such as loading source files and defining common variables. -This can be done with the ``@everywhere`` macro: +This can be done with the ``@everywhere`` macro:: @everywhere include("defs.jl") diff --git a/doc/manual/strings.rst b/doc/manual/strings.rst index bbe04b98dd7f8..d5f539cc17b5f 100644 --- a/doc/manual/strings.rst +++ b/doc/manual/strings.rst @@ -454,9 +454,13 @@ Non-Standard String Literals There are situations when you want to construct a string or use string semantics, but the behavior of the standard string construct is not quite what is needed. For these kinds of situations, Julia provides -*non-standard string literals*. A non-standard string literal looks like +:ref:`non-standard string literals `. +A non-standard string literal looks like a regular double-quoted string literal, but is immediately prefixed by an identifier, and doesn't behave quite like a normal string literal. +Regular expressions, as described below, are one example of a non-standard +string literal. Other examples are given in the :ref:`metaprogramming +` section. Regular Expressions ------------------- diff --git a/doc/manual/types.rst b/doc/manual/types.rst index cb92fa4105ff9..29f62bbb5b033 100644 --- a/doc/manual/types.rst +++ b/doc/manual/types.rst @@ -70,27 +70,6 @@ the need to write code that explicitly uses types. Some kinds of programming, however, become clearer, simpler, faster and more robust with declared types. -.. raw:: html - - - Type Declarations ----------------- @@ -150,7 +129,7 @@ The "declaration" behavior only occurs in specific contexts:: In value contexts, such as ``f(x::Int8)``, the ``::`` is a type assertion again and not a declaration. Note that these declarations -cannot be used in global scope currently, in the REPL, since julia +cannot be used in global scope currently, in the REPL, since Julia does not yet have constant-type globals. .. _man-abstract-types: @@ -266,7 +245,7 @@ the standard bits types are all defined in the language itself:: bitstype 64 Int64 <: Signed bitstype 64 Uint64 <: Unsigned -The general syntaxes for declaration of a bitstypes are:: +The general syntaxes for declaration of a ``bitstype`` are:: bitstype «bits» «name» bitstype «bits» «name» <: «supertype» @@ -300,7 +279,7 @@ Composite Types --------------- `Composite types `_ -are called records, structures ("structs" in C), or objects in various +are called records, structures (``structs`` in C), or objects in various languages. A composite type is a collection of named fields, an instance of which can be treated as a single value. In many languages, composite types are the only kind of user-definable type, and they are by far the @@ -400,7 +379,7 @@ Immutable Composite Types ------------------------- It is also possible to define *immutable* composite types by using -the keyword ``immutable`` instead of ``type``: +the keyword ``immutable`` instead of ``type``:: immutable Complex real::Float64 diff --git a/doc/manual/variables-and-scoping.rst b/doc/manual/variables-and-scoping.rst index 42dc19fda1795..ab9673ff89f42 100644 --- a/doc/manual/variables-and-scoping.rst +++ b/doc/manual/variables-and-scoping.rst @@ -1,14 +1,8 @@ .. _man-variables-and-scoping: -*********************** - Variables and Scoping -*********************** - -Until now, we have simply used variables without any explanation. -Julia's usage of variables closely resembles that of other dynamic -languages, so we have hopefully gotten away with this liberty. In what -follows, however, we address this oversight and provide details of how -variables are used, declared, and scoped in Julia. +******************** + Scope of Variables +******************** The *scope* of a variable is the region of code within which a variable is visible. Variable scoping helps avoid variable naming conflicts. The diff --git a/doc/manual/variables.rst b/doc/manual/variables.rst new file mode 100644 index 0000000000000..6737545b1c97f --- /dev/null +++ b/doc/manual/variables.rst @@ -0,0 +1,75 @@ + +*********** + Variables +*********** + +Julia provides an extremely flexible system for naming variables. +Capitalization carries no semantic meaning, nor does the first letter of a +variable. :: + + julia> ix = 1.0 + 1.0 + + julia> y = -3 + -3 + + julia> Z = "My string" + "My string" + + julia> customary_phrase = "Hello world!" + "Hello world!" + + julia> BeginningOfTheUniversalDeclarationOfHumanRightsInChinese = "人人生而自由,在尊严和权力上一律平等。" + "人人生而自由,在尊严和权力上一律平等。" + +They can even be given Unicode names:: + + julia> δ = 0.00001 + 0.00001 + + julia> 안녕하세요 = "Hello" + "Hello" + +Julia will even let you redefine built-in constants and functions if needed:: + + julia> pi + + 3.141592653589793 + + julia> pi = 3 + Warning: imported binding for pi overwritten in module Main + 3 + + julia> pi + 3 + + julia> sqrt = 4 + 4 + +However, this is obviously not recommended to avoid potential confusion. + +The only explicitly disallowed names for variables are the names of built-in +statements:: + + julia> else = false + ERROR: syntax: unexpected else + + julia> try = "No" + ERROR: syntax: unexpected = + + +Stylistic convention +==================== + +While Julia imposes few restrictions on valid names, it has become useful to +adopt the following conventions on names in Julia: + +- Names of variables are in lower case, with word separation indicated by + underscores (``'\_'``). +- Names of ``Type``\ s begin with a capital letter and word separation is + shown with CamelCase instead of underscores. +- Names of ``function``\ s and ``macro``\s are in lower case, without + underscores. +- Functions that modify their inputs have names that end in ``!``. These + functions are sometimes called mutating functions or in-place functions. +