From 7bbc17cb5d89ae472a75358889742276c0bb4960 Mon Sep 17 00:00:00 2001 From: Katharine Hyatt Date: Mon, 26 Jun 2017 20:56:41 -0500 Subject: [PATCH] More doctests and cleanup for intfuncs (#22515) * More doctests and cleanup for intfuncs * Also more doctests for arrays * More doctests and Example{s} inserting * Doctests for DAYS * Fix some failing doctests * "fix" failing OffsetArray test * Address more comments * fix dropstored! * Fix leading space * fix typo (cherry picked from commit de746144cfe76de27b08874b4e37da2f8d10935f) --- base/abstractarray.jl | 6 +- base/abstractarraymath.jl | 7 + base/array.jl | 102 +++++++- base/arraymath.jl | 7 + base/bitarray.jl | 3 + base/combinatorics.jl | 9 +- base/docs/helpdb/Base.jl | 280 ++++++++++++++++++++-- base/essentials.jl | 2 +- base/intfuncs.jl | 129 +++++++++- base/linalg/eigen.jl | 4 +- base/linalg/generic.jl | 29 ++- base/multidimensional.jl | 46 +++- base/permuteddimsarray.jl | 3 +- base/random.jl | 197 ++++++++++++++- base/reducedim.jl | 15 ++ base/sort.jl | 11 + base/sparse/sparsematrix.jl | 92 ++++++- base/sparse/sparsevector.jl | 16 ++ doc/src/manual/faq.md | 4 +- doc/src/manual/mathematical-operations.md | 6 +- doc/src/manual/types.md | 2 +- 21 files changed, 917 insertions(+), 53 deletions(-) diff --git a/base/abstractarray.jl b/base/abstractarray.jl index e2e5749998e36..6360769c785c5 100644 --- a/base/abstractarray.jl +++ b/base/abstractarray.jl @@ -801,7 +801,7 @@ A[iter] = 0 If you supply more than one `AbstractArray` argument, `eachindex` will create an iterable object that is fast for all arguments (a `UnitRange` -if all inputs have fast linear indexing, a `CartesianRange` +if all inputs have fast linear indexing, a [`CartesianRange`](@ref) otherwise). If the arrays have different sizes and/or dimensionalities, `eachindex` returns an iterable that spans the largest range along each dimension. @@ -1718,6 +1718,7 @@ For multiple iterable arguments, `f` is called elementwise. `foreach` should be used instead of `map` when the results of `f` are not needed, for example in `foreach(println, array)`. +# Example ```jldoctest julia> a = 1:3:7; @@ -1745,6 +1746,7 @@ colons go in this expression. The results are concatenated along the remaining d For example, if `dims` is `[1,2]` and `A` is 4-dimensional, `f` is called on `A[:,:,i,j]` for all `i` and `j`. +# Examples ```jldoctest julia> a = reshape(collect(1:16),(2,2,2,2)) 2×2×2×2 Array{Int64,4}: @@ -1871,6 +1873,7 @@ map(f, A::Union{AbstractArray,AbstractSet,Associative}) = collect_similar(A, Gen Transform collection `c` by applying `f` to each element. For multiple collection arguments, apply `f` elementwise. +# Examples ```jldoctest julia> map(x -> x * 2, [1, 2, 3]) 3-element Array{Int64,1}: @@ -1913,6 +1916,7 @@ end Like [`map`](@ref), but stores the result in `destination` rather than a new collection. `destination` must be at least as large as the first collection. +# Example ```jldoctest julia> x = zeros(3); diff --git a/base/abstractarraymath.jl b/base/abstractarraymath.jl index 058170e3d5041..0430293b46737 100644 --- a/base/abstractarraymath.jl +++ b/base/abstractarraymath.jl @@ -16,6 +16,7 @@ Reshape the array `a` as a one-dimensional column vector. The resulting array shares the same underlying data as `a`, so modifying one will also modify the other. +# Example ```jldoctest julia> a = [1 2 3; 4 5 6] 2×3 Array{Int64,2}: @@ -48,6 +49,7 @@ Remove the dimensions specified by `dims` from array `A`. Elements of `dims` must be unique and within the range `1:ndims(A)`. `size(A,i)` must equal 1 for all `i` in `dims`. +# Example ```jldoctest julia> a = reshape(collect(1:4),(2,2,1,1)) 2×2×1×1 Array{Int64,4}: @@ -101,6 +103,7 @@ imag(x::AbstractArray{<:Real}) = zero(x) Return all the data of `A` where the index for dimension `d` equals `i`. Equivalent to `A[:,:,...,i,:,:,...]` where `i` is in position `d`. +# Example ```jldoctest julia> A = [1 2 3 4; 5 6 7 8] 2×4 Array{Int64,2}: @@ -125,6 +128,7 @@ end Reverse `A` in dimension `d`. +# Example ```jldoctest julia> b = [1 2; 3 4] 2×2 Array{Int64,2}: @@ -177,6 +181,7 @@ circshift(a::AbstractArray, shiftamt::DimsInteger) = circshift!(similar(a), a, s Circularly shift the data in an array. The second argument is a vector giving the amount to shift in each dimension. +# Example ```jldoctest julia> b = reshape(collect(1:16), (4,4)) 4×4 Array{Int64,2}: @@ -281,6 +286,7 @@ end Construct a matrix by repeating the given matrix (or vector) `m` times in dimension 1 and `n` times in dimension 2. +# Examples ```jldoctest julia> repmat([1, 2, 3], 2) 6-element Array{Int64,1}: @@ -337,6 +343,7 @@ repeated. The i-th element of `outer` specifies the number of times that a slice i-th dimension of `A` should be repeated. If `inner` or `outer` are omitted, no repetition is performed. +# Examples ```jldoctest julia> repeat(1:2, inner=2) 4-element Array{Int64,1}: diff --git a/base/array.jl b/base/array.jl index 2fe19b8f50f3f..633dfed5c1469 100644 --- a/base/array.jl +++ b/base/array.jl @@ -272,6 +272,26 @@ end `m`-by-`n` identity matrix. The default element type is [`Float64`](@ref). + +# Examples + +```jldoctest +julia> eye(3, 4) +3×4 Array{Float64,2}: + 1.0 0.0 0.0 0.0 + 0.0 1.0 0.0 0.0 + 0.0 0.0 1.0 0.0 + +julia> eye(2, 2) +2×2 Array{Float64,2}: + 1.0 0.0 + 0.0 1.0 + +julia> eye(Int, 2, 2) +2×2 Array{Int64,2}: + 1 0 + 0 1 +``` """ function eye(::Type{T}, m::Integer, n::Integer) where T a = zeros(T,m,n) @@ -293,6 +313,19 @@ eye(::Type{T}, n::Integer) where {T} = eye(T, n, n) `n`-by-`n` identity matrix. The default element type is [`Float64`](@ref). + +# Examples +```jldoctest +julia> eye(Int, 2) +2×2 Array{Int64,2}: + 1 0 + 0 1 + +julia> eye(2) +2×2 Array{Float64,2}: + 1.0 0.0 + 0.0 1.0 +``` """ eye(n::Integer) = eye(Float64, n) @@ -382,6 +415,7 @@ Return an `Array` of all items in a collection or iterator. For associative coll `Pair{KeyType, ValType}`. If the argument is array-like or is an iterator with the `HasShape()` trait, the result will have the same shape and number of dimensions as the argument. +# Example ```jldoctest julia> collect(1:2:13) 7-element Array{Int64,1}: @@ -658,6 +692,7 @@ end Insert the elements of `items` to the beginning of `a`. +# Example ```jldoctest julia> prepend!([3],[1,2]) 3-element Array{Int64,1}: @@ -710,25 +745,27 @@ Resize `a` to contain `n` elements. If `n` is smaller than the current collectio length, the first `n` elements will be retained. If `n` is larger, the new elements are not guaranteed to be initialized. +# Examples ```jldoctest julia> resize!([6, 5, 4, 3, 2, 1], 3) 3-element Array{Int64,1}: 6 5 4 -``` -```julia-repl -julia> resize!([6, 5, 4, 3, 2, 1], 8) -8-element Array{Int64,1}: +julia> a = resize!([6, 5, 4, 3, 2, 1], 8); + +julia> length(a) +8 + +julia> a[1:6] +6-element Array{Int64,1}: 6 5 4 3 2 1 - 0 - 0 ``` """ function resize!(a::Vector, nl::Integer) @@ -763,6 +800,7 @@ end Insert one or more `items` at the beginning of `collection`. +# Example ```jldoctest julia> unshift!([1, 2, 3, 4], 5, 6) 6-element Array{Int64,1}: @@ -796,6 +834,7 @@ end Insert an `item` into `a` at the given `index`. `index` is the index of `item` in the resulting `a`. +# Example ```jldoctest julia> insert!([6, 5, 4, 2, 1], 4, 3) 6-element Array{Int64,1}: @@ -822,6 +861,7 @@ end Remove the item at the given `i` and return the modified `a`. Subsequent items are shifted to fill the resulting gap. +# Example ```jldoctest julia> deleteat!([6, 5, 4, 3, 2, 1], 2) 5-element Array{Int64,1}: @@ -849,6 +889,7 @@ Subsequent items are shifted to fill the resulting gap. `inds` can be either an iterator or a collection of sorted and unique integer indices, or a boolean vector of the same length as `a` with `true` indicating entries to delete. +# Examples ```jldoctest julia> deleteat!([6, 5, 4, 3, 2, 1], 1:2:5) 3-element Array{Int64,1}: @@ -865,8 +906,8 @@ julia> deleteat!([6, 5, 4, 3, 2, 1], [true, false, true, false, true, false]) julia> deleteat!([6, 5, 4, 3, 2, 1], (2, 2)) ERROR: ArgumentError: indices must be unique and sorted Stacktrace: - [1] _deleteat!(::Array{Int64,1}, ::Tuple{Int64,Int64}) at ./array.jl:885 - [2] deleteat!(::Array{Int64,1}, ::Tuple{Int64,Int64}) at ./array.jl:872 + [1] _deleteat!(::Array{Int64,1}, ::Tuple{Int64,Int64}) at ./array.jl:926 + [2] deleteat!(::Array{Int64,1}, ::Tuple{Int64,Int64}) at ./array.jl:913 ``` """ deleteat!(a::Vector, inds) = _deleteat!(a, inds) @@ -924,6 +965,7 @@ Subsequent items are shifted left to fill the resulting gap. If specified, replacement values from an ordered collection will be spliced in place of the removed item. +# Examples ```jldoctest splice! julia> A = [6, 5, 4, 3, 2, 1]; splice!(A, 5) 2 @@ -994,6 +1036,7 @@ place of the removed items. To insert `replacement` before an index `n` without removing any items, use `splice!(collection, n:n-1, replacement)`. +# Example ```jldoctest splice! julia> splice!(A, 4:3, 2) 0-element Array{Int64,1} @@ -1150,6 +1193,7 @@ cat(n::Integer, x::Integer...) = reshape([x...], (ntuple(x->1, n-1)..., length(x Find the next linear index >= `i` of a non-zero element of `A`, or `0` if not found. +# Examples ```jldoctest julia> A = [0 0; 1 0] 2×2 Array{Int64,2}: @@ -1178,6 +1222,7 @@ end Return the linear index of the first non-zero value in `A` (determined by `A[i]!=0`). Returns `0` if no such value is found. +# Examples ```jldoctest julia> A = [0 0; 1 0] 2×2 Array{Int64,2}: @@ -1186,6 +1231,9 @@ julia> A = [0 0; 1 0] julia> findfirst(A) 2 + +julia> findfirst(zeros(3)) +0 ``` """ findfirst(A) = findnext(A, 1) @@ -1195,6 +1243,7 @@ findfirst(A) = findnext(A, 1) Find the next linear index >= `i` of an element of `A` equal to `v` (using `==`), or `0` if not found. +# Examples ```jldoctest julia> A = [1 4; 2 2] 2×2 Array{Int64,2}: @@ -1222,6 +1271,7 @@ end Return the linear index of the first element equal to `v` in `A`. Returns `0` if `v` is not found. +# Examples ```jldoctest julia> A = [4 6; 2 2] 2×2 Array{Int64,2}: @@ -1242,6 +1292,7 @@ findfirst(A, v) = findnext(A, v, 1) Find the next linear index >= `i` of an element of `A` for which `predicate` returns `true`, or `0` if not found. +# Examples ```jldoctest julia> A = [1 4; 2 2] 2×2 Array{Int64,2}: @@ -1270,6 +1321,7 @@ end Return the linear index of the first element of `A` for which `predicate` returns `true`. Returns `0` if there is no such element. +# Examples ```jldoctest julia> A = [1 4; 2 2] 2×2 Array{Int64,2}: @@ -1290,6 +1342,7 @@ findfirst(testf::Function, A) = findnext(testf, A, 1) Find the previous linear index <= `i` of a non-zero element of `A`, or `0` if not found. +# Examples ```jldoctest julia> A = [0 0; 1 2] 2×2 Array{Int64,2}: @@ -1316,6 +1369,7 @@ end Return the linear index of the last non-zero value in `A` (determined by `A[i]!=0`). Returns `0` if there is no non-zero value in `A`. +# Examples ```jldoctest julia> A = [1 0; 1 0] 2×2 Array{Int64,2}: @@ -1341,6 +1395,7 @@ findlast(A) = findprev(A, length(A)) Find the previous linear index <= `i` of an element of `A` equal to `v` (using `==`), or `0` if not found. +# Examples ```jldoctest julia> A = [0 0; 1 2] 2×2 Array{Int64,2}: @@ -1367,6 +1422,7 @@ end Return the linear index of the last element equal to `v` in `A`. Returns `0` if there is no element of `A` equal to `v`. +# Examples ```jldoctest julia> A = [1 2; 2 1] 2×2 Array{Int64,2}: @@ -1391,6 +1447,7 @@ findlast(A, v) = findprev(A, v, length(A)) Find the previous linear index <= `i` of an element of `A` for which `predicate` returns `true`, or `0` if not found. +# Examples ```jldoctest julia> A = [4 6; 1 2] 2×2 Array{Int64,2}: @@ -1417,6 +1474,7 @@ end Return the linear index of the last element of `A` for which `predicate` returns `true`. Returns `0` if there is no such element. +# Examples ```jldoctest julia> A = [1 2; 3 4] 2×2 Array{Int64,2}: @@ -1438,6 +1496,7 @@ findlast(testf::Function, A) = findprev(testf, A, length(A)) Return a vector `I` of the linear indexes of `A` where `f(A[I])` returns `true`. If there are no such elements of `A`, find returns an empty array. +# Examples ```jldoctest julia> A = [1 2; 3 4] 2×2 Array{Int64,2}: @@ -1448,6 +1507,9 @@ julia> find(isodd,A) 2-element Array{Int64,1}: 1 2 + +julia> find(isodd, [2, 4]) +0-element Array{Int64,1} ``` """ function find(testf::Function, A) @@ -1474,6 +1536,7 @@ Return a vector of the linear indexes of the non-zeros in `A` (determined by `A[ common use of this is to convert a boolean array to an array of indexes of the `true` elements. If there are no non-zero elements of `A`, `find` returns an empty array. +# Examples ```jldoctest julia> A = [true false; false true] 2×2 Array{Bool,2}: @@ -1484,6 +1547,9 @@ julia> find(A) 2-element Array{Int64,1}: 1 4 + +julia> find(zeros(3)) +0-element Array{Int64,1} ``` """ function find(A) @@ -1512,6 +1578,7 @@ Return a vector of indexes for each dimension giving the locations of the non-ze (determined by `A[i]!=0`). If there are no non-zero elements of `A`, `findn` returns a 2-tuple of empty arrays. +# Examples ```jldoctest julia> A = [1 2 0; 0 0 3; 0 4 0] 3×3 Array{Int64,2}: @@ -1552,6 +1619,7 @@ end Return a tuple `(I, J, V)` where `I` and `J` are the row and column indexes of the non-zero values in matrix `A`, and `V` is a vector of the non-zero values. +# Example ```jldoctest julia> A = [1 2 0; 0 0 3; 0 4 0] 3×3 Array{Int64,2}: @@ -1592,6 +1660,7 @@ all elements are `NaN`. The collection must not be empty. +# Examples ```jldoctest julia> findmax([8,0.1,-9,pi]) (8.0, 1) @@ -1630,6 +1699,7 @@ all elements are `NaN`. The collection must not be empty. +# Examples ```jldoctest julia> findmin([8,0.1,-9,pi]) (-9.0, 3) @@ -1668,6 +1738,7 @@ elements are `NaN`. The collection must not be empty. +# Examples ```jldoctest julia> indmax([8,0.1,-9,pi]) 1 @@ -1690,6 +1761,7 @@ elements are `NaN`. The collection must not be empty. +# Examples ```jldoctest julia> indmin([8,0.1,-9,pi]) 3 @@ -1711,6 +1783,7 @@ Returns a vector containing the highest index in `b` for each value in `a` that is a member of `b` . The output vector contains 0 wherever `a` is not a member of `b`. +# Examples ```jldoctest julia> a = ['a', 'b', 'c', 'b', 'd', 'a']; @@ -1742,6 +1815,7 @@ end Returns the indices of elements in collection `a` that appear in collection `b`. +# Examples ```jldoctest julia> a = collect(1:3:15) 5-element Array{Int64,1}: @@ -1803,6 +1877,7 @@ end Return a copy of `collection`, removing elements for which `function` is `false`. For associative collections, the function is passed two arguments (key and value). +# Examples ```jldocttest julia> a = 1:10 1:10 @@ -1814,6 +1889,15 @@ julia> filter(isodd, a) 5 7 9 + +julia> d = Dict(1=>"a", 2=>"b") +Dict{Int64,String} with 2 entries: + 2 => "b" + 1 => "a" + +julia> filter((x,y)->isodd(x), d) +Dict{Int64,String} with 1 entry: + 1 => "a" ``` """ filter(f, As::AbstractArray) = As[map(f, As)::AbstractArray{Bool}] @@ -1889,6 +1973,7 @@ both arguments must be collections, and both will be iterated over. In particula `setdiff(set,element)` where `element` is a potential member of `set`, will not work in general. +# Example ```jldoctest julia> setdiff([1,2,3],[3,4,5]) 2-element Array{Int64,1}: @@ -1922,6 +2007,7 @@ symdiff(a, b) = union(setdiff(a,b), setdiff(b,a)) Construct the symmetric difference of elements in the passed in sets or arrays. Maintains order with arrays. +# Example ```jldoctest julia> symdiff([1,2,3],[3,4,5],[4,5,6]) 3-element Array{Int64,1}: diff --git a/base/arraymath.jl b/base/arraymath.jl index 54ac4418c5e45..020dd9f736fbc 100644 --- a/base/arraymath.jl +++ b/base/arraymath.jl @@ -9,6 +9,7 @@ Transform an array to its complex conjugate in-place. See also [`conj`](@ref). +# Example ```jldoctest julia> A = [1+im 2-im; 2+2im 3+im] 2×2 Array{Complex{Int64},2}: @@ -116,6 +117,7 @@ end Rotate matrix `A` left 90 degrees. +# Example ```jldoctest julia> a = [1 2; 3 4] 2×2 Array{Int64,2}: @@ -143,6 +145,7 @@ end Rotate matrix `A` right 90 degrees. +# Example ```jldoctest julia> a = [1 2; 3 4] 2×2 Array{Int64,2}: @@ -169,6 +172,7 @@ end Rotate matrix `A` 180 degrees. +# Example ```jldoctest julia> a = [1 2; 3 4] 2×2 Array{Int64,2}: @@ -196,6 +200,7 @@ end Rotate matrix `A` left 90 degrees an integer `k` number of times. If `k` is zero or a multiple of four, this is equivalent to a `copy`. +# Examples ```jldoctest julia> a = [1 2; 3 4] 2×2 Array{Int64,2}: @@ -235,6 +240,7 @@ end Rotate matrix `A` right 90 degrees an integer `k` number of times. If `k` is zero or a multiple of four, this is equivalent to a `copy`. +# Examples ```jldoctest julia> a = [1 2; 3 4] 2×2 Array{Int64,2}: @@ -269,6 +275,7 @@ rotr90(A::AbstractMatrix, k::Integer) = rotl90(A,-k) Rotate matrix `A` 180 degrees an integer `k` number of times. If `k` is even, this is equivalent to a `copy`. +# Examples ```jldoctest julia> a = [1 2; 3 4] 2×2 Array{Int64,2}: diff --git a/base/bitarray.jl b/base/bitarray.jl index 261853f02aa1c..7fd2ba6b65a0f 100644 --- a/base/bitarray.jl +++ b/base/bitarray.jl @@ -1145,6 +1145,7 @@ end Performs a bitwise not operation on `B`. See [`~`](@ref). +# Example ```jldoctest julia> A = trues(2,2) 2×2 BitArray{2}: @@ -1497,6 +1498,7 @@ Performs a left rotation operation, returning a new `BitVector`. `i` controls how far to rotate the bits. See also [`rol!`](@ref). +# Examples ```jldoctest julia> A = BitArray([true, true, false, false, true]) 5-element BitArray{1}: @@ -1566,6 +1568,7 @@ Performs a right rotation operation on `B`, returning a new `BitVector`. `i` controls how far to rotate the bits. See also [`ror!`](@ref). +# Examples ```jldoctest julia> A = BitArray([true, true, false, false, true]) 5-element BitArray{1}: diff --git a/base/combinatorics.jl b/base/combinatorics.jl index 920f6c23d944e..7cf2eccbbaef8 100644 --- a/base/combinatorics.jl +++ b/base/combinatorics.jl @@ -61,6 +61,7 @@ end Returns `true` if `v` is a valid permutation. +# Examples ```jldoctest julia> isperm([1; 2]) true @@ -112,8 +113,9 @@ to verify that `p` is a permutation. To return a new permutation, use `v[p]`. Note that this is generally faster than `permute!(v,p)` for large vectors. -See also [`ipermute!`](@ref) +See also [`ipermute!`](@ref). +# Example ```jldoctest julia> A = [1, 1, 3, 4]; @@ -157,8 +159,9 @@ end """ ipermute!(v, p) -Like `permute!`, but the inverse of the given permutation is applied. +Like [`permute!`](@ref), but the inverse of the given permutation is applied. +# Example ```jldoctest julia> A = [1, 1, 3, 4]; @@ -182,6 +185,7 @@ ipermute!(a, p::AbstractVector) = ipermute!!(a, copymutable(p)) Return the inverse permutation of `v`. If `B = A[v]`, then `A == B[invperm(v)]`. +# Example ```jldoctest julia> v = [2; 4; 3; 1]; @@ -233,6 +237,7 @@ invperm(a::Tuple) = (invperm([a...])...,) Next integer greater than or equal to `n` that can be written as ``\\prod k_i^{p_i}`` for integers ``p_1``, ``p_2``, etc. +# Example ```jldoctest julia> nextprod([2, 3], 105) 108 diff --git a/base/docs/helpdb/Base.jl b/base/docs/helpdb/Base.jl index 4f67be21924dc..22d05c4aefeb2 100644 --- a/base/docs/helpdb/Base.jl +++ b/base/docs/helpdb/Base.jl @@ -9,6 +9,7 @@ Fill array `A` with the value `x`. If `x` is an object reference, all elements w the same object. `fill!(A, Foo())` will return `A` filled with the result of evaluating `Foo()` once. +# Examples ```jldoctest julia> A = zeros(2,3) 2×3 Array{Float64,2}: @@ -81,6 +82,7 @@ Subtraction operator. A string giving the literal bit representation of a number. +# Example ```jldoctest julia> bits(4) "0000000000000000000000000000000000000000000000000000000000000100" @@ -97,6 +99,7 @@ bits Construct a 1-d array of the specified type. This is usually called with the syntax `Type[]`. Element values can be specified using `Type[a,b,c,...]`. +# Example ```jldoctest julia> Int8[1, 2, 3] 3-element Array{Int8,1}: @@ -120,6 +123,7 @@ Returns a subset of array `A` as specified by `inds`, where each `ind` may be an `Int`, a `Range`, or a `Vector`. See the manual section on [array indexing](@ref man-array-indexing) for details. +# Examples ```jldoctest julia> A = [1 2; 3 4] 2×2 Array{Int64,2}: @@ -149,6 +153,7 @@ getindex(::AbstractArray, inds...) Retrieve the value(s) stored at the given key or index within a collection. The syntax `a[i,j,...]` is converted by the compiler to `getindex(a, i, j, ...)`. +# Example ```jldoctest julia> A = Dict("a" => 1, "b" => 2) Dict{String,Int64} with 2 entries: @@ -219,6 +224,7 @@ unsafe_copy!(dest::Array, d, src::Array, so, N) Create a Float32 from `x`. If `x` is not exactly representable then `mode` determines how `x` is rounded. +# Examples ```jldoctest julia> Float32(1/3, RoundDown) 0.3333333f0 @@ -310,6 +316,7 @@ Mmap.mmap(io, ::BitArray, dims = ?, offset = ?) Update `collection`, removing elements for which `function` is `false`. For associative collections, the function is passed two arguments (key and value). +# Example ```jldoctest julia> filter!(isodd, collect(1:10)) 5-element Array{Int64,1}: @@ -327,6 +334,7 @@ filter! Size, in bytes, of the canonical binary representation of the given DataType `T`, if any. +# Examples ```jldoctest julia> sizeof(Float32) 4 @@ -341,7 +349,7 @@ If `T` does not have a specific size, an error is thrown. julia> sizeof(Base.LinAlg.LU) ERROR: argument is an abstract type; size is indeterminate Stacktrace: - [1] sizeof(::Type{T} where T) at ./essentials.jl:159 + [1] sizeof(::Type{T} where T) at ./essentials.jl:150 ``` """ sizeof(::Type) @@ -378,6 +386,7 @@ oftype Insert one or more `items` at the end of `collection`. +# Example ```jldoctest julia> push!([1, 2, 3], 4, 5, 6) 6-element Array{Int64,1}: @@ -399,6 +408,12 @@ push! promote(xs...) Convert all arguments to their common promotion type (if any), and return them all (as a tuple). + +# Example +```jldoctest +julia> promote(Int8(1), Float16(4.5), Float32(4.1)) +(1.0f0, 4.5f0, 4.1f0) +``` """ promote @@ -418,6 +433,7 @@ Create an array of all ones with the same layout as `A`, element type `T` and si The `A` argument can be skipped, which behaves like `Array{Float64,0}()` was passed. For convenience `dims` may also be passed in variadic form. +# Examples ```jldoctest julia> ones(Complex128, 2, 3) 2×3 Array{Complex{Float64},2}: @@ -483,6 +499,23 @@ Returns the range of indices of `a` which compare as equal to `x` (using binary according to the order specified by the `by`, `lt` and `rev` keywords, assuming that `a` is already sorted in that order. Returns an empty range located at the insertion point if `a` does not contain values equal to `x`. + +# Examples + +```jldoctest +julia> a = [4, 3, 2, 1] +4-element Array{Int64,1}: + 4 + 3 + 2 + 1 + +julia> searchsorted(a, 4) +5:4 + +julia> searchsorted(a, 4, rev=true) +1:1 +``` """ searchsorted @@ -549,6 +582,7 @@ print_shortest Construct a tuple of the given objects. +# Example ```jldoctest julia> tuple(1, 'a', pi) (1, 'a', π = 3.1415926535897...) @@ -570,6 +604,7 @@ eachmatch Get a hexadecimal string of the binary representation of a floating point number. +# Example ```jldoctest julia> num2hex(2.2) "400199999999999a" @@ -590,6 +625,7 @@ truncate Compute ``10^x``. +# Examples ```jldoctest julia> exp10(2) 100.0 @@ -605,6 +641,7 @@ exp10 Bitwise and. +# Examples ```jldoctest julia> 4 & 10 0 @@ -618,7 +655,7 @@ julia> 4 & 12 """ select(v, k, [by=,] [lt=,] [rev=false]) -Variant of `select!` which copies `v` before partially sorting it, thereby returning the +Variant of [`select!`](@ref) which copies `v` before partially sorting it, thereby returning the same thing as `select!` but leaving `v` unmodified. """ select @@ -664,6 +701,41 @@ ErrorException reverse(v [, start=1 [, stop=length(v) ]] ) Return a copy of `v` reversed from start to stop. + +# Examples +```jldoctest +julia> A = collect(1:5) +5-element Array{Int64,1}: + 1 + 2 + 3 + 4 + 5 + +julia> reverse(A) +5-element Array{Int64,1}: + 5 + 4 + 3 + 2 + 1 + +julia> reverse(A, 1, 4) +5-element Array{Int64,1}: + 4 + 3 + 2 + 1 + 5 + +julia> reverse(A, 3, 5) +5-element Array{Int64,1}: + 1 + 2 + 5 + 4 + 3 +``` """ reverse @@ -686,15 +758,14 @@ UndefRefError Add the elements of `collection2` to the end of `collection`. +# Examples ```jldoctest julia> append!([1],[2,3]) 3-element Array{Int64,1}: 1 2 3 -``` -```jldoctest julia> append!([1, 2, 3], [4, 5, 6]) 6-element Array{Int64,1}: 1 @@ -730,6 +801,7 @@ setdiff! Return `z` which has the magnitude of `x` and the same sign as `y`. +# Examples ```jldoctest julia> copysign(1, -2) -1 @@ -767,6 +839,7 @@ showcompact Extract a named field from a `value` of composite type. The syntax `a.b` calls `getfield(a, :b)`. +# Example ```jldoctest julia> a = 1//2 1//2 @@ -786,6 +859,48 @@ at the position where it would appear if the array were fully sorted via a non-s algorithm. If `k` is a single index, that value is returned; if `k` is a range, an array of values at those indices is returned. Note that `select!` does not fully sort the input array. + +# Examples + +```jldoctest +julia> a = [1, 2, 4, 3, 4] +5-element Array{Int64,1}: + 1 + 2 + 4 + 3 + 4 + +julia> select!(a, 4) +4 + +julia> a +5-element Array{Int64,1}: + 1 + 2 + 3 + 4 + 4 + +julia> a = [1, 2, 4, 3, 4] +5-element Array{Int64,1}: + 1 + 2 + 4 + 3 + 4 + +julia> select!(a, 4, rev=true) +2 + +julia> a +5-element Array{Int64,1}: + 4 + 4 + 3 + 2 + 1 +``` """ select! @@ -795,6 +910,15 @@ select! Create a random ASCII string of length `len`, consisting of upper- and lower-case letters and the digits 0-9. The optional `rng` argument specifies a random number generator, see [Random Numbers](@ref). + +# Example + +```jldoctest +julia> rng = MersenneTwister(1234); + +julia> randstring(rng, 4) +"mbDd" +``` """ randstring @@ -804,6 +928,7 @@ randstring Create a Float64 from `x`. If `x` is not exactly representable then `mode` determines how `x` is rounded. +# Examples ```jldoctest julia> Float64(pi, RoundDown) 3.141592653589793 @@ -821,6 +946,28 @@ Float64(x) ∪(s1,s2...) Construct the union of two or more sets. Maintains order with arrays. + +# Examples +```jldoctest +julia> union([1, 2], [3, 4]) +4-element Array{Int64,1}: + 1 + 2 + 3 + 4 + +julia> union([1, 2], [2, 4]) +3-element Array{Int64,1}: + 1 + 2 + 4 + +julia> union([4, 2], [1, 2]) +3-element Array{Int64,1}: + 4 + 2 + 1 +``` """ union @@ -829,6 +976,7 @@ union The highest finite value representable by the given floating-point DataType `T`. +# Examples ```jldoctest julia> realmax(Float16) Float16(6.55e4) @@ -855,6 +1003,7 @@ serialize The lowest value representable by the given (real) numeric DataType `T`. +# Examples ```jldoctest julia> typemin(Float16) -Inf16 @@ -938,6 +1087,7 @@ cglobal Returns the last index of the collection. +# Example ```jldoctest julia> endof([1,2,4]) 3 @@ -950,6 +1100,7 @@ endof For a given iterable object and iteration state, return the current item and the next iteration state. +# Examples ```jldoctest julia> next(1:5, 3) (3, 4) @@ -1085,9 +1236,9 @@ Return a partial permutation of the vector `v`, according to the order specified if `k` is a range) values of a fully sorted version of `v`. If `k` is a single index (Integer), an array of the first `k` indices is returned; if `k` is a range, an array of those indices is returned. Note that the handling of integer values for `k` is different -from `select` in that it returns a vector of `k` elements instead of just the `k` th +from [`select`](@ref) in that it returns a vector of `k` elements instead of just the `k` th element. Also note that this is equivalent to, but more efficient than, calling -`sortperm(...)[k]` +`sortperm(...)[k]`. """ selectperm @@ -1101,6 +1252,15 @@ For example, `reinterpret(Float32, UInt32(7))` interprets the 4 bytes corresponding to `UInt32(7)` as a [`Float32`](@ref). +!!! warning + + It is not allowed to `reinterpret` an array to an element type with a larger alignment then + the alignment of the array. For a normal `Array`, this is the alignment of its element type. + For a reinterpreted array, this is the alignment of the `Array` it was reinterpreted from. + For example, `reinterpret(UInt32, UInt8[0, 0, 0, 0])` is not allowed but + `reinterpret(UInt32, reinterpret(UInt8, Float32[1.0]))` is allowed. + +# Examples ```jldoctest julia> reinterpret(Float32, UInt32(7)) 1.0f-44 @@ -1117,6 +1277,7 @@ reinterpret Bitwise not. +# Examples ```jldoctest julia> ~4 -5 @@ -1135,6 +1296,7 @@ false Byte-swap an integer. Flip the bits of its binary representation. +# Examples ```jldoctest julia> a = bswap(4) 288230376151711744 @@ -1162,6 +1324,18 @@ maxintfloat delete!(collection, key) Delete the mapping for the given key in a collection, and return the collection. + +# Example +```jldoctest +julia> d = Dict("a"=>1, "b"=>2) +Dict{String,Int64} with 2 entries: + "b" => 2 + "a" => 1 + +julia> delete!(d, "b") +Dict{String,Int64} with 1 entry: + "a" => 1 +``` """ delete! @@ -1171,6 +1345,20 @@ delete! Returns the index of the first value in `a` greater than or equal to `x`, according to the specified order. Returns `length(a)+1` if `x` is greater than all values in `a`. +`a` is assumed to be sorted. + +# Examples + +```jldoctest +julia> searchsortedfirst([1, 2, 4, 5, 14], 4) +3 + +julia> searchsortedfirst([1, 2, 4, 5, 14], 4, rev=true) +1 + +julia> searchsortedfirst([1, 2, 4, 5, 14], 15) +6 +``` """ searchsortedfirst @@ -1200,7 +1388,7 @@ typejoin """ selectperm!(ix, v, k, [alg=,] [by=,] [lt=,] [rev=false,] [initialized=false]) -Like `selectperm`, but accepts a preallocated index vector `ix`. If `initialized` is `false` +Like [`selectperm`](@ref), but accepts a preallocated index vector `ix`. If `initialized` is `false` (the default), ix is initialized to contain the values `1:length(ix)`. """ selectperm! @@ -1224,6 +1412,17 @@ cot Return the value stored for the given key, or the given default value if no mapping for the key is present. + +# Examples +```jldoctest +julia> d = Dict("a"=>1, "b"=>2); + +julia> get(d, "a", 3) +1 + +julia> get(d, "c", 3) +3 +``` """ get(collection,key,default) @@ -1284,6 +1483,7 @@ read(stream, t) Remove the first `item` from `collection`. +# Example ```jldoctest julia> A = [1, 2, 3, 4, 5, 6] 6-element Array{Int64,1}: @@ -1380,6 +1580,7 @@ copy Determine whether a collection is empty (has no elements). +# Examples ```jldoctest julia> isempty([]) true @@ -1434,6 +1635,7 @@ IntSet Create a `Task` (i.e. coroutine) to execute the given function (which must be callable with no arguments). The task exits when this function returns. +# Example ```jldoctest julia> a() = det(rand(1000, 1000)); @@ -1535,7 +1737,7 @@ mean! Test whether `x` is less than `y`, according to a canonical total order. Values that are normally unordered, such as `NaN`, are ordered in an arbitrary but consistent fashion. This -is the default comparison used by `sort`. Non-numeric types with a canonical total order +is the default comparison used by [`sort`](@ref). Non-numeric types with a canonical total order should implement this function. Numeric types only need to implement it if they have special values such as `NaN`. """ @@ -1655,6 +1857,7 @@ show(x) Return `true` if and only if all values of `type1` are also of `type2`. Can also be written using the `<:` infix operator as `type1 <: type2`. +# Examples ```jldoctest julia> issubtype(Int8, Int32) false @@ -1739,6 +1942,7 @@ matchall Return the value stored for the given key, or if no mapping for the key is present, store `key => default`, and return `default`. +# Examples ```jldoctest julia> d = Dict("a"=>1, "b"=>2, "c"=>3); @@ -1765,11 +1969,12 @@ Return the value stored for the given key, or if no mapping for the key is prese `key => f()`, and return `f()`. This is intended to be called using `do` block syntax: - - get!(dict, key) do - # default value calculated here - time() - end +```julia +get!(dict, key) do + # default value calculated here + time() +end +``` """ get!(f::Function,collection,key) @@ -1799,6 +2004,7 @@ For ordered, indexable collections, returns the maximum index `i` for which `get is valid. For unordered collections, returns the number of elements. +# Examples ```jldoctest julia> length(1:5) 5 @@ -1813,7 +2019,21 @@ length(collection) searchsortedlast(a, x, [by=,] [lt=,] [rev=false]) Returns the index of the last value in `a` less than or equal to `x`, according to the -specified order. Returns `0` if `x` is less than all values in `a`. +specified order. Returns `0` if `x` is less than all values in `a`. `a` is assumed to +be sorted. + +# Examples + +```jldoctest +julia> searchsortedlast([1, 2, 4, 5, 14], 4) +3 + +julia> searchsortedlast([1, 2, 4, 5, 14], 4, rev=true) +5 + +julia> searchsortedlast([1, 2, 4, 5, 14], -1) +0 +``` """ searchsortedlast @@ -1912,6 +2132,7 @@ coth Get initial iteration state for an iterable object. +# Examples ```jldoctest julia> start(1:5) 1 @@ -1946,6 +2167,7 @@ isa Test whether we are done iterating. +# Examples ```jldoctest julia> done(1:5, 3) false @@ -1968,6 +2190,7 @@ If `T` is an [`Integer`](@ref) type, an [`InexactError`](@ref) will be raised if is not representable by `T`, for example if `x` is not integer-valued, or is outside the range supported by `T`. +# Examples ```jldoctest julia> convert(Int, 3.0) 3 @@ -2034,6 +2257,7 @@ convert Determine whether the given generic function has a method applicable to the given arguments. +# Examples ```jldoctest julia> function f(x, y) x + y @@ -2117,6 +2341,15 @@ throw ⊊(a,b) -> Bool Determine whether every element of `a` is also in `b`, using [`in`](@ref). + +# Examples +```jldoctest +julia> issubset([1, 2], [1, 2, 3]) +true + +julia> issubset([1, 2, 3], [1, 2]) +false +``` """ issubset(a,b) @@ -2135,7 +2368,7 @@ Create an array of all zeros with the same layout as `A`, element type `T` and s The `A` argument can be skipped, which behaves like `Array{Float64,0}()` was passed. For convenience `dims` may also be passed in variadic form. - +# Examples ```jldoctest julia> zeros(1) 1-element Array{Float64,1}: @@ -2200,6 +2433,18 @@ isvalid(T,value) Convert a number to an unsigned integer. If the argument is signed, it is reinterpreted as unsigned without checking for negative values. + +# Examples +```jldoctest +julia> unsigned(-2) +0xfffffffffffffffe + +julia> unsigned(2) +0x0000000000000002 + +julia> signed(unsigned(-2)) +-2 +``` """ unsigned @@ -2217,6 +2462,7 @@ reverseind Returns `true` if the value of the sign of `x` is negative, otherwise `false`. +# Examples ```jldoctest julia> signbit(-4) true @@ -2308,6 +2554,7 @@ If `x` is a type, return a "larger" type (for numeric types, this will be a type with at least as much range and precision as the argument, and usually more). Otherwise `x` is converted to `widen(typeof(x))`. +# Examples ```jldoctest julia> widen(Int32) Int64 @@ -2350,6 +2597,7 @@ Val Bitwise or. +# Examples ```jldoctest julia> 4 | 10 14 @@ -2366,6 +2614,7 @@ Base.:(|) Delete and return the mapping for `key` if it exists in `collection`, otherwise return `default`, or throw an error if `default` is not specified. +# Examples ```jldoctest julia> d = Dict("a"=>1, "b"=>2, "c"=>3); @@ -2388,6 +2637,7 @@ pop!(collection,key,?) Remove the last item in `collection` and return it. +# Examples ```jldoctest julia> A=[1, 2, 3, 4, 5, 6] 6-element Array{Int64,1}: diff --git a/base/essentials.jl b/base/essentials.jl index 6e06e23302d1d..7c522aaed415d 100644 --- a/base/essentials.jl +++ b/base/essentials.jl @@ -314,7 +314,7 @@ end Colons (:) are used to signify indexing entire objects or dimensions at once. Very few operations are defined on Colons directly; instead they are converted -by `to_indices` to an internal vector type (`Base.Slice`) to represent the +by [`to_indices`](@ref) to an internal vector type (`Base.Slice`) to represent the collection of indices they span before being used. """ struct Colon diff --git a/base/intfuncs.jl b/base/intfuncs.jl index 4f34d7a7ace29..e25098f2d81b3 100644 --- a/base/intfuncs.jl +++ b/base/intfuncs.jl @@ -7,6 +7,7 @@ Greatest common (positive) divisor (or zero if `x` and `y` are both zero). +# Examples ```jldoctest julia> gcd(6,9) 3 @@ -51,6 +52,8 @@ end lcm(x,y) Least common (non-negative) multiple. + +# Examples ```jldoctest julia> lcm(2,3) 6 @@ -86,12 +89,11 @@ Computes the greatest common (positive) divisor of `x` and `y` and their Bézout coefficients, i.e. the integer coefficients `u` and `v` that satisfy ``ux+vy = d = gcd(x,y)``. ``gcdx(x,y)`` returns ``(d,u,v)``. +# Examples ```jldoctest julia> gcdx(12, 42) (6, -3, 1) -``` -```jldoctest julia> gcdx(240, 46) (2, -9, 47) ``` @@ -131,6 +133,7 @@ Take the inverse of `x` modulo `m`: `y` such that ``x y = 1 \\pmod m``, with ``div(x,y) = 0``. This is undefined for ``m = 0``, or if ``gcd(x,m) \\neq 1``. +# Examples ```jldoctest julia> invmod(2,5) 3 @@ -225,12 +228,22 @@ const HWNumber = Union{HWReal, Complex{<:HWReal}, Rational{<:HWReal}} Compute ``x^p \\pmod m``. +# Examples ```jldoctest julia> powermod(2, 6, 5) 4 julia> mod(2^6, 5) 4 + +julia> powermod(5, 2, 20) +5 + +julia> powermod(5, 2, 19) +6 + +julia> powermod(5, 3, 19) +11 ``` """ function powermod(x::Integer, p::Integer, m::T) where T<:Integer @@ -265,6 +278,7 @@ powermod(x::Integer, p::Integer, m::Union{Int128,UInt128}) = oftype(m, powermod( The smallest power of two not less than `n`. Returns 0 for `n==0`, and returns `-nextpow2(-n)` for negative arguments. +# Examples ```jldoctest julia> nextpow2(16) 16 @@ -282,9 +296,13 @@ nextpow2(x::Integer) = reinterpret(typeof(x),x < 0 ? -nextpow2(unsigned(-x)) : n The largest power of two not greater than `n`. Returns 0 for `n==0`, and returns `-prevpow2(-n)` for negative arguments. +# Examples ```jldoctest julia> prevpow2(5) 4 + +julia> prevpow2(0) +0 ``` """ prevpow2(x::Unsigned) = one(x) << unsigned((sizeof(x)<<3)-leading_zeros(x)-1) @@ -295,6 +313,7 @@ prevpow2(x::Integer) = reinterpret(typeof(x),x < 0 ? -prevpow2(unsigned(-x)) : p Test whether `n` is a power of two. +# Examples ```jldoctest julia> ispow2(4) true @@ -311,12 +330,19 @@ ispow2(x::Integer) = x > 0 && count_ones(x) == 1 The smallest `a^n` not less than `x`, where `n` is a non-negative integer. `a` must be greater than 1, and `x` must be greater than 0. +# Examples ```jldoctest julia> nextpow(2, 7) 8 julia> nextpow(2, 9) 16 + +julia> nextpow(5, 20) +25 + +julia> nextpow(4, 16) +16 ``` See also [`prevpow`](@ref). @@ -336,14 +362,20 @@ end The largest `a^n` not greater than `x`, where `n` is a non-negative integer. `a` must be greater than 1, and `x` must not be less than 1. +# Examples ```jldoctest julia> prevpow(2, 7) 4 julia> prevpow(2, 9) 8 -``` +julia> prevpow(5, 20) +5 + +julia> prevpow(4, 16) +16 +``` See also [`nextpow`](@ref). """ function prevpow(a::Real, x::Real) @@ -423,12 +455,22 @@ integer `n` written in base `b` (i.e. equal to `ndigits(n, b)` in this case). The base `b` must not be in `[-1, 0, 1]`. +# Examples ```jldoctest julia> Base.ndigits0z(0, 16) 0 julia> Base.ndigits(0, 16) 1 + +julia> Base.ndigits0z(0) +0 + +julia> Base.ndigits0z(10, 2) +4 + +julia> Base.ndigits0z(10) +2 ``` See also [`ndigits`](@ref). @@ -441,6 +483,7 @@ ndigits0z Compute the number of digits in integer `n` written in base `b`. The base `b` must not be in `[-1, 0, 1]`. +# Examples ```jldoctest julia> ndigits(12345) 5 @@ -572,21 +615,49 @@ bin """ hex(n, pad::Int=1) -Convert an integer to a hexadecimal string, optionally specifying a number of digits to pad to. +Convert an integer to a hexadecimal string, optionally specifying a number of +digits to pad to. + +```jldoctest +julia> hex(20) +"14" + +julia> hex(20, 3) +"014" +``` """ hex """ oct(n, pad::Int=1) -Convert an integer to an octal string, optionally specifying a number of digits to pad to. +Convert an integer to an octal string, optionally specifying a number of digits +to pad to. + +```jldoctest +julia> oct(20) +"24" + +julia> oct(20, 3) +"024" +``` """ oct """ dec(n, pad::Int=1) -Convert an integer to a decimal string, optionally specifying a number of digits to pad to. +Convert an integer to a decimal string, optionally specifying a number of digits +to pad to. + +# Examples +```jldoctest +julia> dec(20) +"20" + +julia> dec(20, 3) +"020" +``` """ dec @@ -602,6 +673,30 @@ bits(x::Union{Int128,UInt128}) = bin(reinterpret(UInt128,x),128) Returns an array with element type `T` (default `Int`) of the digits of `n` in the given base, optionally padded with zeros to a specified size. More significant digits are at higher indexes, such that `n == sum([digits[k]*base^(k-1) for k=1:length(digits)])`. + +# Examples +```jldoctest +julia> digits(10, 10) +2-element Array{Int64,1}: + 0 + 1 + +julia> digits(10, 2) +4-element Array{Int64,1}: + 0 + 1 + 0 + 1 + +julia> digits(10, 2, 6) +6-element Array{Int64,1}: + 0 + 1 + 0 + 1 + 0 + 0 +``` """ digits(n::Integer, base::T=10, pad::Integer=1) where {T<:Integer} = digits(T, n, base, pad) @@ -616,6 +711,25 @@ end Fills an array of the digits of `n` in the given base. More significant digits are at higher indexes. If the array length is insufficient, the least significant digits are filled up to the array length. If the array length is excessive, the excess portion is filled with zeros. + +# Examples +```jldoctest +julia> digits!([2,2,2,2], 10, 2) +4-element Array{Int64,1}: + 0 + 1 + 0 + 1 + +julia> digits!([2,2,2,2,2,2], 10, 2) +6-element Array{Int64,1}: + 0 + 1 + 0 + 1 + 0 + 0 +``` """ function digits!(a::AbstractArray{T,1}, n::Integer, base::Integer=10) where T<:Integer 2 <= base || throw(ArgumentError("base must be ≥ 2, got $base")) @@ -659,10 +773,11 @@ function factorial(n::Integer) end """ - binomial(n,k) + binomial(n, k) Number of ways to choose `k` out of `n` items. +# Example ```jldoctest julia> binomial(5, 3) 10 diff --git a/base/linalg/eigen.jl b/base/linalg/eigen.jl index 0ef75b84c2246..4280da7c2d196 100644 --- a/base/linalg/eigen.jl +++ b/base/linalg/eigen.jl @@ -228,7 +228,7 @@ julia> A = [0 im; -1 0] julia> eigmax(A) ERROR: DomainError: Stacktrace: - [1] #eigmax#46(::Bool, ::Bool, ::Function, ::Array{Complex{Int64},2}) at ./linalg/eigen.jl:238 + [1] #eigmax#52(::Bool, ::Bool, ::Function, ::Array{Complex{Int64},2}) at ./linalg/eigen.jl:238 [2] eigmax(::Array{Complex{Int64},2}) at ./linalg/eigen.jl:236 ``` """ @@ -270,7 +270,7 @@ julia> A = [0 im; -1 0] julia> eigmin(A) ERROR: DomainError: Stacktrace: - [1] #eigmin#47(::Bool, ::Bool, ::Function, ::Array{Complex{Int64},2}) at ./linalg/eigen.jl:280 + [1] #eigmin#53(::Bool, ::Bool, ::Function, ::Array{Complex{Int64},2}) at ./linalg/eigen.jl:280 [2] eigmin(::Array{Complex{Int64},2}) at ./linalg/eigen.jl:278 ``` """ diff --git a/base/linalg/generic.jl b/base/linalg/generic.jl index 6f44208621bd4..cfce003667412 100644 --- a/base/linalg/generic.jl +++ b/base/linalg/generic.jl @@ -702,6 +702,21 @@ values of `M` have magnitude greater than `tol`. By default, the value of `tol` is the largest dimension of `M` multiplied by the [`eps`](@ref) of the [`eltype`](@ref) of `M`. + +# Example +```jldoctest +julia> rank(eye(3)) +3 + +julia> rank(diagm([1, 0, 2])) +2 + +julia> rank(diagm([1, 0.001, 2]), 0.1) +2 + +julia> rank(diagm([1, 0.001, 2]), 0.00001) +3 +``` """ rank(A::AbstractMatrix, tol::Real) = mapreduce(x -> x > tol, +, 0, svdvals(A)) function rank(A::AbstractMatrix) @@ -852,7 +867,7 @@ condskeel(A::AbstractMatrix, x::AbstractVector, p::Real=Inf) = norm(abs.(inv(A)) Test whether a matrix is symmetric. -# Example +# Examples ```jldoctest julia> a = [1 2; 2 -1] @@ -892,7 +907,7 @@ issymmetric(x::Number) = x == x Test whether a matrix is Hermitian. -# Example +# Examples ```jldoctest julia> a = [1 2; 2 -1] @@ -932,7 +947,7 @@ ishermitian(x::Number) = (x == conj(x)) Test whether a matrix is upper triangular. -# Example +# Examples ```jldoctest julia> a = [1 2; 2 -1] @@ -967,7 +982,7 @@ end Test whether a matrix is lower triangular. -# Example +# Examples ```jldoctest julia> a = [1 2; 2 -1] @@ -1002,7 +1017,7 @@ end Test whether a matrix is diagonal. -# Example +# Examples ```jldoctest julia> a = [1 2; 2 -1] @@ -1224,7 +1239,7 @@ logabsdet(A::AbstractMatrix) = logabsdet(lufact(A)) Log of matrix determinant. Equivalent to `log(det(M))`, but may provide increased accuracy and/or speed. -# Example +# Examples ```jldoctest julia> M = [1 0; 2 2] @@ -1322,7 +1337,7 @@ Normalize the vector `v` so that its `p`-norm equals unity, i.e. `norm(v, p) == vecnorm(v, p) == 1`. See also [`normalize!`](@ref) and [`vecnorm`](@ref). -# Example +# Examples ```jldoctest julia> a = [1,2,4]; diff --git a/base/multidimensional.jl b/base/multidimensional.jl index 129bb5fe224a7..5384f66020e40 100644 --- a/base/multidimensional.jl +++ b/base/multidimensional.jl @@ -27,6 +27,37 @@ module IteratorsMD A `CartesianIndex` is sometimes produced by [`eachindex`](@ref), and always when iterating with an explicit [`CartesianRange`](@ref). + + # Example + + ```jldoctest + julia> A = reshape(collect(1:16), (2, 2, 2, 2)) + 2×2×2×2 Array{Int64,4}: + [:, :, 1, 1] = + 1 3 + 2 4 + + [:, :, 2, 1] = + 5 7 + 6 8 + + [:, :, 1, 2] = + 9 11 + 10 12 + + [:, :, 2, 2] = + 13 15 + 14 16 + + julia> A[CartesianIndex((1, 1, 1, 1))] + 1 + + julia> A[CartesianIndex((1, 1, 1, 2))] + 9 + + julia> A[CartesianIndex((1, 1, 2, 1))] + 5 + ``` """ struct CartesianIndex{N} <: AbstractCartesianIndex{N} I::NTuple{N,Int} @@ -111,6 +142,18 @@ module IteratorsMD Consequently these can be useful for writing algorithms that work in arbitrary dimensions. + + ```jldoctest + julia> foreach(println, CartesianRange((2, 2, 2))) + CartesianIndex{3}((1, 1, 1)) + CartesianIndex{3}((2, 1, 1)) + CartesianIndex{3}((1, 2, 1)) + CartesianIndex{3}((2, 2, 1)) + CartesianIndex{3}((1, 1, 2)) + CartesianIndex{3}((2, 1, 2)) + CartesianIndex{3}((1, 2, 2)) + CartesianIndex{3}((2, 2, 2)) + ``` """ struct CartesianRange{I<:CartesianIndex} start::I @@ -850,7 +893,7 @@ Circularly shift the data in `src`, storing the result in The `dest` array must be distinct from the `src` array (they cannot alias each other). -See also `circshift`. +See also [`circshift`](@ref). """ @noinline function circshift!(dest::AbstractArray{T,N}, src, shiftamt::DimsInteger) where {T,N} dest === src && throw(ArgumentError("dest and src must be separate arrays")) @@ -903,6 +946,7 @@ their indices; any offset results in a (circular) wraparound. If the arrays have overlapping indices, then on the domain of the overlap `dest` agrees with `src`. +# Example ```julia-repl julia> src = reshape(collect(1:16), (4,4)) 4×4 Array{Int64,2}: diff --git a/base/permuteddimsarray.jl b/base/permuteddimsarray.jl index 8236a781f39c6..fee5d3af0b66b 100644 --- a/base/permuteddimsarray.jl +++ b/base/permuteddimsarray.jl @@ -89,6 +89,7 @@ equivalent to `permutedims(A, [2,1])`. See also: [`PermutedDimsArray`](@ref). +# Example ```jldoctest julia> A = reshape(collect(1:8), (2,2,2)) 2×2×2 Array{Int64,3}: @@ -125,7 +126,7 @@ have `size(dest) == size(src)[perm]` and is completely overwritten. No in-place is supported and unexpected results will happen if `src` and `dest` have overlapping memory regions. -See also [`permutedims`](@ref) +See also [`permutedims`](@ref). """ function Base.permutedims!(dest, src::AbstractArray, perm) Base.checkdims_perm(dest, src, perm) diff --git a/base/random.jl b/base/random.jl index ff8f9cccd39ba..6a46a71f4d591 100644 --- a/base/random.jl +++ b/base/random.jl @@ -93,6 +93,11 @@ MersenneTwister(seed::Vector{UInt32}, state::DSFMT_state) = Create a `MersenneTwister` RNG object. Different RNG objects can have their own seeds, which may be useful for generating different streams of random numbers. + +# Example +```jldoctest +julia> rng = MersenneTwister(1234); +``` """ MersenneTwister(seed) = srand(MersenneTwister(Vector{UInt32}(), DSFMT_state()), seed) @@ -290,6 +295,20 @@ rand(r::AbstractArray) = rand(GLOBAL_RNG, r) Populate the array `A` with random values. If the indexable collection `coll` is specified, the values are picked randomly from `coll`. This is equivalent to `copy!(A, rand(rng, coll, size(A)))` or `copy!(A, rand(rng, eltype(A), size(A)))` but without allocating a new array. + +# Example + +```jldoctest +julia> rng = MersenneTwister(1234); + +julia> rand!(rng, zeros(5)) +5-element Array{Float64,1}: + 0.590845 + 0.766797 + 0.566237 + 0.460085 + 0.794026 +``` """ rand!(A::AbstractArray, r::AbstractArray) = rand!(GLOBAL_RNG, A, r) @@ -692,6 +711,25 @@ end bitrand([rng=GLOBAL_RNG], [dims...]) Generate a `BitArray` of random boolean values. + +# Example + +```jldoctest +julia> rng = MersenneTwister(1234); + +julia> bitrand(rng, 10) +10-element BitArray{1}: + true + true + true + false + true + false + false + true + false + true +``` """ bitrand(r::AbstractRNG, dims::Dims) = rand!(r, BitArray(dims)) bitrand(r::AbstractRNG, dims::Int...) = rand!(r, BitArray(dims)) @@ -1199,7 +1237,23 @@ const ziggurat_exp_r = 7.6971174701310497140446280481 Generate a normally-distributed random number of type `T` with mean 0 and standard deviation 1. Optionally generate an array of normally-distributed random numbers. The `Base` module currently provides an implementation for the types -[`Float16`](@ref), [`Float32`](@ref), and [`Float64`](@ref) (the default). +[`Float16`](@ref), [`Float32`](@ref), and [`Float64`](@ref) (the default), and their +[`Complex`](@ref) counterparts. When the type argument is complex, the values are drawn +from the circularly symmetric complex normal distribution. + +# Examples + +```jldoctest +julia> rng = MersenneTwister(1234); + +julia> randn(rng, Complex128) +0.6133070881429037 - 0.6376291670853887im + +julia> randn(rng, Complex64, (2, 4)) +2×4 Array{Complex{Float32},2}: + -0.349649-0.638457im 0.376756-0.192146im -0.396334-0.0136413im -0.585317+0.0778497im + 0.611224+1.56403im 0.355204-0.365563im 0.0905552+1.31012im -0.177608+0.261427im +``` """ @inline function randn(rng::AbstractRNG=GLOBAL_RNG) @inbounds begin @@ -1234,6 +1288,21 @@ Generate a random number of type `T` according to the exponential distribution w Optionally generate an array of such random numbers. The `Base` module currently provides an implementation for the types [`Float16`](@ref), [`Float32`](@ref), and [`Float64`](@ref) (the default). + +# Examples + +```jldoctest +julia> rng = MersenneTwister(1234); + +julia> randexp(rng, Float32) +2.4835055f0 + +julia> randexp(rng, 3, 3) +3×3 Array{Float64,2}: + 1.5167 1.30652 0.344435 + 0.604436 2.78029 0.418516 + 0.695867 0.693292 0.643644 +``` """ @inline function randexp(rng::AbstractRNG=GLOBAL_RNG) @inbounds begin @@ -1260,6 +1329,20 @@ end Fill the array `A` with normally-distributed (mean 0, standard deviation 1) random numbers. Also see the [`rand`](@ref) function. + +# Example + +```jldoctest +julia> rng = MersenneTwister(1234); + +julia> randn!(rng, zeros(5)) +5-element Array{Float64,1}: + 0.867347 + -0.901744 + -0.494479 + -0.902914 + 0.864401 +``` """ function randn! end @@ -1267,6 +1350,20 @@ function randn! end randexp!([rng=GLOBAL_RNG], A::AbstractArray) -> A Fill the array `A` with random numbers following the exponential distribution (with scale 1). + +# Example + +```jldoctest +julia> rng = MersenneTwister(1234); + +julia> randexp!(rng, zeros(5)) +5-element Array{Float64,1}: + 2.48351 + 1.5167 + 0.604436 + 0.695867 + 1.30652 +``` """ function randexp! end @@ -1316,6 +1413,15 @@ end Generates a version 1 (time-based) universally unique identifier (UUID), as specified by RFC 4122. Note that the Node ID is randomly generated (does not identify the host) according to section 4.5 of the RFC. + +# Example + +```jldoctest +julia> rng = MersenneTwister(1234); + +julia> Base.Random.uuid1(rng) +2cc938da-5937-11e7-196e-0f4ef71aa64b +``` """ function uuid1(rng::AbstractRNG=GLOBAL_RNG) u = rand(rng, UInt128) @@ -1345,6 +1451,14 @@ end Generates a version 4 (random or pseudo-random) universally unique identifier (UUID), as specified by RFC 4122. + +# Example +```jldoctest +julia> rng = MersenneTwister(1234); + +julia> Base.Random.uuid4(rng) +82015f10-44cc-4827-996e-0f4ef71aa64b +``` """ function uuid4(rng::AbstractRNG=GLOBAL_RNG) u = rand(rng, UInt128) @@ -1357,6 +1471,15 @@ end uuid_version(u::UUID) -> Integer Inspects the given UUID and returns its version (see RFC 4122). + +# Example + +```jldoctest +julia> rng = MersenneTwister(1234); + +julia> Base.Random.uuid_version(Base.Random.uuid4(rng)) +4 +``` """ function uuid_version(u::UUID) Int((u.value >> 76) & 0xf) @@ -1472,6 +1595,31 @@ end In-place version of [`shuffle`](@ref): randomly permute the array `v` in-place, optionally supplying the random-number generator `rng`. + +# Example + +```jldoctest +julia> rng = MersenneTwister(1234); + +julia> shuffle!(rng, collect(1:16)) +16-element Array{Int64,1}: + 2 + 15 + 5 + 14 + 1 + 9 + 10 + 6 + 11 + 3 + 16 + 7 + 4 + 12 + 8 + 13 +``` """ function shuffle!(r::AbstractRNG, a::AbstractVector) n = length(a) @@ -1494,6 +1642,25 @@ Return a randomly permuted copy of `v`. The optional `rng` argument specifies a number generator (see [Random Numbers](@ref)). To permute `v` in-place, see [`shuffle!`](@ref). To obtain randomly permuted indices, see [`randperm`](@ref). + +# Example + +```jldoctest +julia> rng = MersenneTwister(1234); + +julia> shuffle(rng, collect(1:10)) +10-element Array{Int64,1}: + 6 + 1 + 10 + 2 + 3 + 9 + 5 + 7 + 4 + 8 +``` """ shuffle(r::AbstractRNG, a::AbstractVector) = shuffle!(r, copymutable(a)) shuffle(a::AbstractVector) = shuffle(GLOBAL_RNG, a) @@ -1505,6 +1672,19 @@ Construct a random permutation of length `n`. The optional `rng` argument specif number generator (see [Random Numbers](@ref)). To randomly permute a arbitrary vector, see [`shuffle`](@ref) or [`shuffle!`](@ref). + +# Example + +```jldoctest +julia> rng = MersenneTwister(1234); + +julia> randperm(rng, 4) +4-element Array{Int64,1}: + 2 + 1 + 4 + 3 +``` """ function randperm(r::AbstractRNG, n::Integer) a = Vector{typeof(n)}(n) @@ -1531,6 +1711,21 @@ randperm(n::Integer) = randperm(GLOBAL_RNG, n) Construct a random cyclic permutation of length `n`. The optional `rng` argument specifies a random number generator, see [Random Numbers](@ref). + +# Example + +```jldoctest +julia> rng = MersenneTwister(1234); + +julia> randcycle(rng, 6) +6-element Array{Int64,1}: + 3 + 5 + 4 + 6 + 1 + 2 +``` """ function randcycle(r::AbstractRNG, n::Integer) a = Vector{typeof(n)}(n) diff --git a/base/reducedim.jl b/base/reducedim.jl index a2ba674ee6d64..e857f579b3b55 100644 --- a/base/reducedim.jl +++ b/base/reducedim.jl @@ -219,6 +219,7 @@ reducedim!(op, R::AbstractArray{RT}, A::AbstractArray) where {RT} = Evaluates to the same as `reducedim(op, map(f, A), region, f(v0))`, but is generally faster because the intermediate array is avoided. +# Examples ```jldoctest julia> a = reshape(collect(1:16), (4,4)) 4×4 Array{Int64,2}: @@ -252,6 +253,7 @@ The associativity of the reduction is implementation-dependent; if you need a pa associativity, e.g. left-to-right, you should write your own loop. See documentation for [`reduce`](@ref). +# Examples ```jldoctest julia> a = reshape(collect(1:16), (4,4)) 4×4 Array{Int64,2}: @@ -282,6 +284,7 @@ reducedim(op, A::AbstractArray, region) = mapreducedim(identity, op, A, region) Sum elements of an array over the given dimensions. +# Examples ```jldoctest julia> A = [1 2; 3 4] 2×2 Array{Int64,2}: @@ -305,6 +308,7 @@ sum(A, dims) Sum elements of `A` over the singleton dimensions of `r`, and write results to `r`. +# Examples ```jldoctest julia> A = [1 2; 3 4] 2×2 Array{Int64,2}: @@ -328,6 +332,7 @@ sum!(r, A) Multiply elements of an array over the given dimensions. +# Examples ```jldoctest julia> A = [1 2; 3 4] 2×2 Array{Int64,2}: @@ -351,6 +356,7 @@ prod(A, dims) Multiply elements of `A` over the singleton dimensions of `r`, and write results to `r`. +# Examples ```jldoctest julia> A = [1 2; 3 4] 2×2 Array{Int64,2}: @@ -399,6 +405,7 @@ maximum(A, dims) Compute the maximum value of `A` over the singleton dimensions of `r`, and write results to `r`. +# Examples ```jldoctest julia> A = [1 2; 3 4] 2×2 Array{Int64,2}: @@ -424,6 +431,7 @@ Compute the minimum value of an array over the given dimensions. See also the [`min(a,b)`](@ref) function to take the minimum of two or more arguments, which can be applied elementwise to arrays via `min.(a,b)`. +# Examples ```jldoctest julia> A = [1 2; 3 4] 2×2 Array{Int64,2}: @@ -447,6 +455,7 @@ minimum(A, dims) Compute the minimum value of `A` over the singleton dimensions of `r`, and write results to `r`. +# Examples ```jldoctest julia> A = [1 2; 3 4] 2×2 Array{Int64,2}: @@ -470,6 +479,7 @@ minimum!(r, A) Test whether all values along the given dimensions of an array are `true`. +# Examples ```jldoctest julia> A = [true false; true true] 2×2 Array{Bool,2}: @@ -493,6 +503,7 @@ all(A::AbstractArray, dims) Test whether all values in `A` along the singleton dimensions of `r` are `true`, and write results to `r`. +# Examples ```jldoctest julia> A = [true false; true false] 2×2 Array{Bool,2}: @@ -516,6 +527,7 @@ all!(r, A) Test whether any values along the given dimensions of an array are `true`. +# Examples ```jldoctest julia> A = [true false; true false] 2×2 Array{Bool,2}: @@ -540,6 +552,7 @@ any(::AbstractArray,dims) Test whether any values in `A` along the singleton dimensions of `r` are `true`, and write results to `r`. +# Examples ```jldoctest julia> A = [true false; true false] 2×2 Array{Bool,2}: @@ -637,6 +650,7 @@ end For an array input, returns the value and index of the minimum over the given region. +# Examples ```jldoctest julia> A = [1 2; 3 4] 2×2 Array{Int64,2}: @@ -675,6 +689,7 @@ end For an array input, returns the value and index of the maximum over the given region. +# Examples ```jldoctest julia> A = [1 2; 3 4] 2×2 Array{Int64,2}: diff --git a/base/sort.jl b/base/sort.jl index 846723518a9b7..cc71c26177f1f 100644 --- a/base/sort.jl +++ b/base/sort.jl @@ -63,6 +63,7 @@ end Test whether a vector is in sorted order. The `lt`, `by` and `rev` keywords modify what order is considered to be sorted just as they do for [`sort`](@ref). +# Examples ```jldoctest julia> issorted([1, 2, 3]) true @@ -447,6 +448,8 @@ options are independent and can be used together in all possible combinations: i and `lt` are specified, the `lt` function is applied to the result of the `by` function; `rev=true` reverses whatever ordering specified via the `by` and `lt` keywords. +# Examples + ```jldoctest julia> v = [3, 1, 2]; sort!(v); v 3-element Array{Int64,1}: @@ -522,6 +525,8 @@ end Variant of [`sort!`](@ref) that returns a sorted copy of `v` leaving `v` itself unmodified. +# Examples + ```jldoctest julia> v = [3, 1, 2]; @@ -578,6 +583,8 @@ specified using the same keywords as `sort!`. See also [`sortperm!`](@ref). +# Examples + ```jldoctest julia> v = [3, 1, 2]; @@ -626,6 +633,8 @@ end Like [`sortperm`](@ref), but accepts a preallocated index vector `ix`. If `initialized` is `false` (the default), `ix` is initialized to contain the values `1:length(v)`. +# Examples + ```jldoctest julia> v = [3, 1, 2]; p = zeros(Int, 3); @@ -691,6 +700,8 @@ Sort a multidimensional array `A` along the given dimension. See [`sort!`](@ref) for a description of possible keyword arguments. +# Examples + ```jldoctest julia> A = [4 3; 1 2] 2×2 Array{Int64,2}: diff --git a/base/sparse/sparsematrix.jl b/base/sparse/sparsematrix.jl index 6fca07fa37682..e0db9edd6fe8e 100644 --- a/base/sparse/sparsematrix.jl +++ b/base/sparse/sparsematrix.jl @@ -32,6 +32,7 @@ size(S::SparseMatrixCSC) = (S.m, S.n) Returns the number of stored (filled) elements in a sparse array. +# Example ```jldoctest julia> A = speye(3) 3×3 SparseMatrixCSC{Float64,Int64} with 3 stored entries: @@ -56,6 +57,7 @@ vector points directly to the internal nonzero storage of `A`, and any modifications to the returned vector will mutate `A` as well. See [`rowvals`](@ref) and [`nzrange`](@ref). +# Example ```jldoctest julia> A = speye(3) 3×3 SparseMatrixCSC{Float64,Int64} with 3 stored entries: @@ -80,6 +82,7 @@ vector will mutate `A` as well. Providing access to how the row indices are stored internally can be useful in conjunction with iterating over structural nonzero values. See also [`nonzeros`](@ref) and [`nzrange`](@ref). +# Example ```jldoctest julia> A = speye(3) 3×3 SparseMatrixCSC{Float64,Int64} with 3 stored entries: @@ -348,6 +351,7 @@ full(S::SparseMatrixCSC) = convert(Array, S) Convert a sparse matrix or vector `S` into a dense matrix or vector. +# Example ```jldoctest julia> A = speye(3) 3×3 SparseMatrixCSC{Float64,Int64} with 3 stored entries: @@ -378,6 +382,7 @@ vec(S::SparseMatrixCSC) = S[:] Convert an AbstractMatrix `A` into a sparse matrix. +# Example ```jldoctest julia> A = eye(3) 3×3 Array{Float64,2}: @@ -458,6 +463,7 @@ retained as structural nonzeros; to drop numerical zeros, use [`dropzeros!`](@re For additional documentation and an expert driver, see `Base.SparseArrays.sparse!`. +# Example ```jldoctest julia> Is = [1; 2; 3]; @@ -1001,7 +1007,7 @@ For additional (algorithmic) information, and for versions of these methods that argument checking, see (unexported) parent methods `unchecked_noalias_permute!` and `unchecked_aliasing_permute!`. -See also: [`permute`](@ref) +See also: [`permute`](@ref). """ function permute!{Tv,Ti}(X::SparseMatrixCSC{Tv,Ti}, A::SparseMatrixCSC{Tv,Ti}, p::AbstractVector{<:Integer}, q::AbstractVector{<:Integer}) @@ -1054,6 +1060,39 @@ match `A`'s column count (`length(q) == A.n`). Row-permutation `p`'s length must row count (`length(p) == A.m`). For expert drivers and additional information, see [`permute!`](@ref). + +# Example +```jldoctest +julia> A = spdiagm([1, 2, 3, 4], 0, 4, 4) + spdiagm([5, 6, 7], 1, 4, 4) +4×4 SparseMatrixCSC{Int64,Int64} with 7 stored entries: + [1, 1] = 1 + [1, 2] = 5 + [2, 2] = 2 + [2, 3] = 6 + [3, 3] = 3 + [3, 4] = 7 + [4, 4] = 4 + +julia> permute(A, [4, 3, 2, 1], [1, 2, 3, 4]) +4×4 SparseMatrixCSC{Int64,Int64} with 7 stored entries: + [4, 1] = 1 + [3, 2] = 2 + [4, 2] = 5 + [2, 3] = 3 + [3, 3] = 6 + [1, 4] = 4 + [2, 4] = 7 + +julia> permute(A, [1, 2, 3, 4], [4, 3, 2, 1]) +4×4 SparseMatrixCSC{Int64,Int64} with 7 stored entries: + [3, 1] = 7 + [4, 1] = 4 + [2, 2] = 6 + [3, 2] = 3 + [1, 3] = 5 + [2, 3] = 2 + [1, 4] = 1 +``` """ function permute{Tv,Ti}(A::SparseMatrixCSC{Tv,Ti}, p::AbstractVector{<:Integer}, q::AbstractVector{<:Integer}) @@ -1078,6 +1117,21 @@ value. This method makes a single sweep through `A`, requiring `O(A.n, nnz(A))`-time for matrices and `O(nnz(A))`-time for vectors and no space beyond that passed in. If `trim` is `true`, this method trims `A.rowval` or `A.nzind` and `A.nzval` to length `nnz(A)` after dropping elements. + +# Example +```jldoctest +julia> A = spdiagm([1, 2, 3, 4]) +4×4 SparseMatrixCSC{Int64,Int64} with 4 stored entries: + [1, 1] = 1 + [2, 2] = 2 + [3, 3] = 3 + [4, 4] = 4 + +julia> Base.SparseArrays.fkeep!(A, (i, j, v) -> isodd(v)) +4×4 SparseMatrixCSC{Int64,Int64} with 2 stored entries: + [1, 1] = 1 + [3, 3] = 3 +``` """ function fkeep!(A::SparseMatrixCSC, f, trim::Bool = true) An = A.n @@ -1153,6 +1207,20 @@ Generates a copy of `A` and removes stored numerical zeros from that copy, optio trimming excess space from the result's `rowval` and `nzval` arrays when `trim` is `true`. For an in-place version and algorithmic information, see [`dropzeros!`](@ref). + +# Example +```jldoctest +julia> A = sparse([1, 2, 3], [1, 2, 3], [1.0, 0.0, 1.0]) +3×3 SparseMatrixCSC{Float64,Int64} with 3 stored entries: + [1, 1] = 1.0 + [2, 2] = 0.0 + [3, 3] = 1.0 + +julia> dropzeros(A) +3×3 SparseMatrixCSC{Float64,Int64} with 2 stored entries: + [1, 1] = 1.0 + [3, 3] = 1.0 +``` """ dropzeros(A::SparseMatrixCSC, trim::Bool = true) = dropzeros!(copy(A), trim) @@ -1263,6 +1331,7 @@ values are sampled from the distribution specified by `rfn` and have the type `t distribution is used in case `rfn` is not specified. The optional `rng` argument specifies a random number generator, see [Random Numbers](@ref). +# Example ```jldoctest julia> rng = MersenneTwister(1234); @@ -1314,6 +1383,7 @@ with the specified (independent) probability `p` of any entry being nonzero, where nonzero values are sampled from the normal distribution. The optional `rng` argument specifies a random number generator, see [Random Numbers](@ref). +# Example ```jldoctest julia> rng = MersenneTwister(1234); @@ -1334,6 +1404,7 @@ sprandn(m::Integer, n::Integer, density::AbstractFloat) = sprandn(GLOBAL_RNG,m,n Create a sparse array with the same structure as that of `S`, but with every nonzero element having the value `1.0`. +# Example ```jldoctest julia> A = sparse([1,2,3,4],[2,4,3,1],[5.,4.,3.,2.]) 4×4 SparseMatrixCSC{Float64,Int64} with 4 stored entries: @@ -1363,6 +1434,7 @@ sparse array will not contain any nonzero values. No storage will be allocated for nonzero values during construction. The type defaults to [`Float64`](@ref) if not specified. +# Examples ```jldoctest julia> spzeros(3, 3) 3×3 SparseMatrixCSC{Float64,Int64} with 0 stored entries @@ -1391,6 +1463,7 @@ speye(m::Integer, n::Integer) = speye(Float64, m, n) Create a sparse identity matrix with the same size as `S`. +# Example ```jldoctest julia> A = sparse([1,2,3,4],[2,4,3,1],[5.,4.,3.,2.]) 4×4 SparseMatrixCSC{Float64,Int64} with 4 stored entries: @@ -2817,6 +2890,22 @@ stored and otherwise do nothing. Derivative forms: dropstored!(A::SparseMatrixCSC, i::Integer, J::AbstractVector{<:Integer}) dropstored!(A::SparseMatrixCSC, I::AbstractVector{<:Integer}, j::Integer) + +# Example +```jldoctest +julia> A = spdiagm([1, 2, 3, 4]) +4×4 SparseMatrixCSC{Int64,Int64} with 4 stored entries: + [1, 1] = 1 + [2, 2] = 2 + [3, 3] = 3 + [4, 4] = 4 + +julia> Base.SparseArrays.dropstored!(A, [1, 2], [1, 1]) +4×4 SparseMatrixCSC{Int64,Int64} with 3 stored entries: + [2, 2] = 2 + [3, 3] = 3 + [4, 4] = 4 +``` """ function dropstored!(A::SparseMatrixCSC, I::AbstractVector{<:Integer}, J::AbstractVector{<:Integer}) @@ -3199,6 +3288,7 @@ one diagonal, `B` can be a vector (instead of a tuple) and `d` can be the diagon (instead of a tuple), defaulting to 0 (diagonal). Optionally, `m` and `n` specify the size of the resulting sparse matrix. +# Example ```jldoctest julia> spdiagm(([1,2,3,4],[4,3,2,1]),(-1,1)) 5×5 SparseMatrixCSC{Int64,Int64} with 8 stored entries: diff --git a/base/sparse/sparsevector.jl b/base/sparse/sparsevector.jl index 63daae89a130a..7922954c13248 100644 --- a/base/sparse/sparsevector.jl +++ b/base/sparse/sparsevector.jl @@ -253,6 +253,7 @@ setindex!(x::SparseVector{Tv,Ti}, v, i::Integer) where {Tv,Ti<:Integer} = Drop entry `x[i]` from `x` if `x[i]` is stored and otherwise do nothing. +# Examples ```jldoctest julia> x = sparsevec([1, 3], [1.0, 2.0]) 3-element SparseVector{Float64,Int64} with 2 stored entries: @@ -305,6 +306,7 @@ convert(::Type{SparseVector}, s::SparseMatrixCSC{Tv,Ti}) where {Tv,Ti} = Convert a vector `A` into a sparse vector of length `m`. +# Example ```jldoctest julia> sparsevec([1.0, 2.0, 0.0, 0.0, 3.0, 0.0]) 6-element SparseVector{Float64,Int64} with 3 stored entries: @@ -1928,6 +1930,20 @@ Generates a copy of `x` and removes numerical zeros from that copy, optionally t excess space from the result's `nzind` and `nzval` arrays when `trim` is `true`. For an in-place version and algorithmic information, see [`dropzeros!`](@ref). + +# Example +```jldoctest +julia> A = sparsevec([1, 2, 3], [1.0, 0.0, 1.0]) +3-element SparseVector{Float64,Int64} with 3 stored entries: + [1] = 1.0 + [2] = 0.0 + [3] = 1.0 + +julia> dropzeros(A) +3-element SparseVector{Float64,Int64} with 2 stored entries: + [1] = 1.0 + [3] = 1.0 +``` """ dropzeros(x::SparseVector, trim::Bool = true) = dropzeros!(copy(x), trim) diff --git a/doc/src/manual/faq.md b/doc/src/manual/faq.md index 462eb8c3b72da..7c5263a2f27c6 100644 --- a/doc/src/manual/faq.md +++ b/doc/src/manual/faq.md @@ -235,8 +235,8 @@ ERROR: DomainError: Cannot raise an integer x to a negative power -n. Make x a float by adding a zero decimal (e.g. 2.0^-n instead of 2^-n), or write 1/x^n, float(x)^-n, or (x//1)^-n. Stacktrace: - [1] power_by_squaring(::Int64, ::Int64) at ./intfuncs.jl:170 - [2] literal_pow(::Base.#^, ::Int64, ::Type{Val{-5}}) at ./intfuncs.jl:205 + [1] power_by_squaring(::Int64, ::Int64) at ./intfuncs.jl:173 + [2] literal_pow(::Base.#^, ::Int64, ::Type{Val{-5}}) at ./intfuncs.jl:208 ``` This behavior is an inconvenient consequence of the requirement for type-stability. In the case diff --git a/doc/src/manual/mathematical-operations.md b/doc/src/manual/mathematical-operations.md index a6e8da1fff8f3..71ef3fa77c464 100644 --- a/doc/src/manual/mathematical-operations.md +++ b/doc/src/manual/mathematical-operations.md @@ -397,7 +397,7 @@ julia> Int8(127) julia> Int8(128) ERROR: InexactError() Stacktrace: - [1] Int8(::Int64) at ./sysimg.jl:24 + [1] Int8(::Int64) at ./sysimg.jl:102 julia> Int8(127.0) 127 @@ -411,8 +411,8 @@ Stacktrace: julia> Int8(128.0) ERROR: InexactError() Stacktrace: - [1] convert(::Type{Int8}, ::Float64) at ./float.jl:658 - [2] Int8(::Float64) at ./sysimg.jl:24 + [1] convert(::Type{Int8}, ::Float64) at ./float.jl:659 + [2] Int8(::Float64) at ./sysimg.jl:102 julia> 127 % Int8 127 diff --git a/doc/src/manual/types.md b/doc/src/manual/types.md index 97c59738623ec..e9cc055b3784c 100644 --- a/doc/src/manual/types.md +++ b/doc/src/manual/types.md @@ -651,7 +651,7 @@ ERROR: MethodError: Cannot `convert` an object of type Float64 to an object of t This may have arisen from a call to the constructor Point{Float64}(...), since type constructors fall back to convert methods. Stacktrace: - [1] Point{Float64}(::Float64) at ./sysimg.jl:24 + [1] Point{Float64}(::Float64) at ./sysimg.jl:102 julia> Point{Float64}(1.0,2.0,3.0) ERROR: MethodError: no method matching Point{Float64}(::Float64, ::Float64, ::Float64)