diff --git a/base/abstractarray.jl b/base/abstractarray.jl index 81f373aa751447..66488402584d08 100644 --- a/base/abstractarray.jl +++ b/base/abstractarray.jl @@ -127,11 +127,41 @@ _length(A) = length(A) endof(a::AbstractArray) = length(a) first(a::AbstractArray) = a[first(eachindex(a))] +""" + first(coll) + +Get the first element of an iterable collection. Returns the start point of a +`Range` even if it is empty. + +```jldoctest +julia> first(2:2:10) +2 + +julia> first([1; 2; 3; 4]) +1 +``` +""" function first(itr) state = start(itr) done(itr, state) && throw(ArgumentError("collection must be non-empty")) next(itr, state)[1] end + +""" + last(coll) + +Get the last element of an ordered collection, if it can be computed in O(1) time. This is +accomplished by calling [`endof`](@ref) to get the last index. Returns the end +point of a `Range` even if it is empty. + +```jldoctest +julia> last(1:2:10) +9 + +julia> last([1; 2; 3; 4]) +4 +``` +""" last(a) = a[end] """ diff --git a/base/bitarray.jl b/base/bitarray.jl index 46a56ce9345fde..726080162f6b56 100644 --- a/base/bitarray.jl +++ b/base/bitarray.jl @@ -1301,6 +1301,23 @@ function (|)(B::BitArray, x::Bool) end (|)(x::Bool, B::BitArray) = B | x +""" + xor(x, y) + ⊻(x, y) + +Bitwise exclusive or of `x` and `y`. The infix operation +`a ⊻ b` is a synonym for `xor(a,b)`, and +`⊻` can be typed by tab-completing `\\xor` +or `\\veebar` in the Julia REPL. + +```jldoctest +julia> [true; true; false] ⊻ [true; false; false] +3-element Array{Bool,1}: + false + true + false +``` +""" function xor(B::BitArray, x::Bool) x ? ~B : copy(B) end diff --git a/base/bool.jl b/base/bool.jl index 8a524dbb0d29e3..398572b2613b7a 100644 --- a/base/bool.jl +++ b/base/bool.jl @@ -14,6 +14,23 @@ typemax(::Type{Bool}) = true ## boolean operations ## +""" + !(x) + +Boolean not. + +```jldoctest +julia> !true +false + +julia> !false +true + +julia> ![true false true] +1×3 Array{Bool,2}: + false true false +``` +""" function !(x::Bool) ## We need a better heuristic to detect this automatically @_pure_meta diff --git a/base/complex.jl b/base/complex.jl index 95ca6ae4cdec2e..c1cd67092b3659 100644 --- a/base/complex.jl +++ b/base/complex.jl @@ -75,6 +75,19 @@ real(T::Type) = typeof(real(zero(T))) real{T<:Real}(::Type{T}) = T real{T<:Real}(::Type{Complex{T}}) = T +""" + isreal(x) -> Bool + +Test whether `x` or all its elements are numerically equal to some real number. + +```jldoctest +julia> isreal(5.) +true + +julia> isreal([4.; complex(0,1)]) +false +``` +""" isreal(x::Real) = true isreal(z::Complex) = iszero(imag(z)) """ diff --git a/base/dict.jl b/base/dict.jl index 5950b8adb3aaac..a595115bac16e6 100644 --- a/base/dict.jl +++ b/base/dict.jl @@ -283,6 +283,23 @@ function sizehint!(d::Dict, newsz) rehash!(d, newsz) end +""" + empty!(collection) -> collection + +Remove all elements from a `collection`. + +```jldoctest +julia> A = Dict("a" => 1, "b" => 2) +Dict{String,Int64} with 2 entries: + "b" => 2 + "a" => 1 + +julia> empty!(A); + +julia> A +Dict{String,Int64} with 0 entries +``` +""" function empty!{K,V}(h::Dict{K,V}) fill!(h.slots, 0x0) sz = length(h.slots) diff --git a/base/docs/helpdb/Base.jl b/base/docs/helpdb/Base.jl index b8667fcf127116..95540ee5bdf6d8 100644 --- a/base/docs/helpdb/Base.jl +++ b/base/docs/helpdb/Base.jl @@ -2,13 +2,6 @@ # Base -""" - systemerror(sysfunc, iftrue) - -Raises a `SystemError` for `errno` with the descriptive string `sysfunc` if `iftrue` is `true` -""" -systemerror - """ fill!(A, x) @@ -49,32 +42,6 @@ Read binary data from an I/O stream or file, filling in `array`. """ read! -""" - empty!(collection) -> collection - -Remove all elements from a `collection`. - -```jldoctest -julia> A = Dict("a" => 1, "b" => 2) -Dict{String,Int64} with 2 entries: - "b" => 2 - "a" => 1 - -julia> empty!(A); - -julia> A -Dict{String,Int64} with 0 entries -``` -""" -empty! - -""" - asin(x) - -Compute the inverse sine of `x`, where the output is in radians. -""" -asin - """ pointer(array [, index]) @@ -86,35 +53,6 @@ Calling `Ref(array[, index])` is generally preferable to this function. """ pointer -""" - //(num, den) - -Divide two integers or rational numbers, giving a `Rational` result. -""" -Base.:(//) - -""" - isinteger(x) -> Bool - -Test whether `x` or all its elements are numerically equal to some integer. - -```jldoctest -julia> isinteger(4.0) -true - -julia> isinteger([1; 2; 5.5]) -false -``` -""" -isinteger - -""" - prod!(r, A) - -Multiply elements of `A` over the singleton dimensions of `r`, and write results to `r`. -""" -prod! - """ cummin(A, [dim]) @@ -122,21 +60,6 @@ Cumulative minimum along a dimension. The dimension defaults to 1. """ cummin -""" - eigfact!(A, [B]) - -Same as [`eigfact`](@ref), but saves space by overwriting the input `A` (and -`B`), instead of creating a copy. -""" -eigfact! - -""" - cosh(x) - -Compute hyperbolic cosine of `x`. -""" -cosh - """ precision(num::AbstractFloat) @@ -145,24 +68,6 @@ the mantissa. """ precision -""" - promote_type(type1, type2) - -Determine a type big enough to hold values of each argument type without loss, whenever -possible. In some cases, where no type exists to which both types can be promoted -losslessly, some loss is tolerated; for example, `promote_type(Int64,Float64)` returns -`Float64` even though strictly, not all `Int64` values can be represented exactly as -`Float64` values. -""" -promote_type - -""" - backtrace() - -Get a backtrace object for the current program point. -""" -backtrace - """ -(x) @@ -276,13 +181,6 @@ Compute the hyperbolic secant of `x` """ sech -""" - acos(x) - -Compute the inverse cosine of `x`, where the output is in radians -""" -acos - """ unsafe_copy!(dest::Ptr{T}, src::Ptr{T}, N) @@ -405,14 +303,6 @@ Bessel function of the second kind of order 0, ``Y_0(x)``. """ bessely0 -""" - any!(r, A) - -Test whether any values in `A` along the singleton dimensions of `r` are `true`, and write -results to `r`. -""" -any! - """ filter!(function, collection) @@ -461,30 +351,6 @@ An operation tried to write to memory that is read-only. """ ReadOnlyMemoryError -""" - last(coll) - -Get the last element of an ordered collection, if it can be computed in O(1) time. This is -accomplished by calling [`endof`](@ref) to get the last index. Returns the end -point of a `Range` even if it is empty. - -```jldoctest -julia> last(1:2:10) -9 - -julia> last([1; 2; 3; 4]) -4 -``` -""" -last - -""" - sinh(x) - -Compute hyperbolic sine of `x`. -""" -sinh - """ ceil([T,] x, [digits, [base]]) @@ -505,21 +371,6 @@ Convert `y` to the type of `x` (`convert(typeof(x), y)`). """ oftype -""" - isfinite(f) -> Bool - -Test whether a number is finite. - -```jldoctest -julia> isfinite(5) -true - -julia> isfinite(NaN32) -false -``` -""" -isfinite - """ push!(collection, items...) -> collection @@ -542,14 +393,6 @@ Use [`append!`](@ref) to add all the elements of another collection to """ push! -""" - prevpow(a, x) - -The largest `a^n` not greater than `x`, where `n` is a non-negative integer. -`a` must be greater than 1, and `x` must not be less than 1. -""" -prevpow - """ promote(xs...) @@ -557,13 +400,6 @@ Convert all arguments to their common promotion type (if any), and return them a """ promote -""" - tan(x) - -Compute tangent of `x`, where `x` is in radians. -""" -tan - """ fd(stream) @@ -656,15 +492,6 @@ Like [`randsubseq`](@ref), but the results are stored in `S` """ randsubseq! -""" - maximum(A, dims) - -Compute the maximum value of an array over the given dimensions. See also the -[`max(a,b)`](@ref) function to take the maximum of two or more arguments, -which can be applied elementwise to arrays via `max.(a,b)`. -""" -maximum(A,dims) - """ redisplay(x) redisplay(d::Display, x) @@ -727,13 +554,6 @@ Determine whether Julia is running an interactive session. """ isinteractive -""" - sum!(r, A) - -Sum elements of `A` over the singleton dimensions of `r`, and write results to `r`. -""" -sum! - """ display(x) display(d::Display, x) @@ -786,22 +606,6 @@ original string, otherwise they must be from distinct character ranges. """ eachmatch -""" - log10(x) - -Compute the logarithm of `x` to base 10. -Throws [`DomainError`](@ref) for negative `Real` arguments. - -```jldoctest -julia> log10(100) -2.0 - -julia> log10(2) -0.3010299956639812 -``` -""" -log10 - """ num2hex(f) @@ -852,14 +656,6 @@ julia> 4 & 12 """ & -""" - cumsum!(B, A, [dim]) - -Cumulative sum of `A` along a dimension, storing the result in `B`. The dimension defaults -to 1. -""" -cumsum! - """ select(v, k, [by=,] [lt=,] [rev=false]) @@ -1020,13 +816,6 @@ test `get(io, :compact, false)` in its normal `show` method. """ showcompact -""" - erfc(x) - -Compute the complementary error function of `x`, defined by ``1 - \\operatorname{erf}(x)``. -""" -erfc - """ getfield(value, name::Symbol) @@ -1054,53 +843,6 @@ array. """ select! -""" - maximum!(r, A) - -Compute the maximum value of `A` over the singleton dimensions of `r`, and write results to `r`. -""" -maximum! - -""" - prod(A, dims) - -Multiply elements of an array over the given dimensions. - -```jldoctest -julia> A = [1 2; 3 4] -2×2 Array{Int64,2}: - 1 2 - 3 4 - -julia> prod(A, 1) -1×2 Array{Int64,2}: - 3 8 - -julia> prod(A, 2) -2×1 Array{Int64,2}: - 2 - 12 -``` -""" -prod(A, dims) - -""" - log1p(x) - -Accurate natural logarithm of `1+x`. Throws [`DomainError`](@ref) for `Real` arguments less than -1. - -There is an experimental variant in the `Base.Math.JuliaLibm` module, which is typically -faster and more accurate. -""" -log1p - -""" - flipsign(x, y) - -Return `x` with its sign flipped if `y` is negative. For example `abs(x) = flipsign(x,x)`. -""" -flipsign - """ randstring([rng,] len=8) @@ -1154,29 +896,6 @@ serialized as all-zero bit patterns (`NULL`). """ serialize -""" - sum(A, dims) - -Sum elements of an array over the given dimensions. - -```jldoctest -julia> A = [1 2; 3 4] -2×2 Array{Int64,2}: - 1 2 - 3 4 - -julia> sum(A, 1) -1×2 Array{Int64,2}: - 4 6 - -julia> sum(A, 2) -2×1 Array{Int64,2}: - 3 - 7 -``` -""" -sum(A, dims) - """ typemin(T) @@ -1191,17 +910,6 @@ Get the concrete type of `x`. """ typeof -""" - log(x) - -Compute the natural logarithm of `x`. Throws [`DomainError`](@ref) for negative `Real` arguments. -Use complex negative arguments to obtain complex results. - -There is an experimental variant in the `Base.Math.JuliaLibm` module, which is typically -faster and more accurate. -""" -log(x) - """ trunc([T,] x, [digits, [base]]) @@ -1285,14 +993,6 @@ respectively. """ cglobal -""" - one(x) - -Get the multiplicative identity element for the type of `x` (`x` can also specify the type -itself). For matrices, returns an identity matrix of the appropriate size and type. -""" -one - """ endof(collection) -> Integer @@ -1312,28 +1012,6 @@ For a given iterable object and iteration state, return the current item and the """ next -""" - log2(x) - -Compute the logarithm of `x` to base 2. Throws [`DomainError`](@ref) for negative `Real` arguments. - -```jldoctest -julia> log2(4) -2.0 - -julia> log2(10) -3.321928094887362 -``` -""" -log2 - -""" - abs2(x) - -Squared absolute value of `x`. -""" -abs2 - """ sizehint!(s, n) @@ -1406,13 +1084,6 @@ floating point number. If the string does not contain a valid number, an error i """ parse(T::Type, str, base=Int) -""" - ^(x, y) - -Exponentiation operator. -""" -Base.:(^)(x, y) - """ position(s) @@ -1480,13 +1151,6 @@ Byte-swap an integer. """ bswap -""" - tanh(x) - -Compute hyperbolic tangent of `x`. -""" -tanh - """ maxintfloat(T) @@ -1555,13 +1219,6 @@ Compute a type that contains both `T` and `S`. """ typejoin -""" - sin(x) - -Compute sine of `x`, where `x` is in radians. -""" -sin - """ selectperm!(ix, v, k, [alg=,] [by=,] [lt=,] [rev=false,] [initialized=false]) @@ -1577,38 +1234,6 @@ Compile the given function `f` for the argument tuple (of types) `args`, but do """ precompile -""" - asinh(x) - -Compute the inverse hyperbolic sine of `x`. -""" -asinh - -""" - minimum(A, dims) - -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)`. - -```jldoctest -julia> A = [1 2; 3 4] -2×2 Array{Int64,2}: - 1 2 - 3 4 - -julia> minimum(A, 1) -1×2 Array{Int64,2}: - 1 2 - -julia> minimum(A, 2) -2×1 Array{Int64,2}: - 1 - 3 -``` -""" -minimum(A,dims) - """ cot(x) @@ -1669,13 +1294,6 @@ Typically, any type that implements `hash` should also implement its own `==` (h """ hash -""" - atanh(x) - -Compute the inverse hyperbolic tangent of `x`. -""" -atanh - """ read(stream::IO, T) @@ -1812,29 +1430,6 @@ The highest value representable by the given (real) numeric `DataType`. """ typemax -""" - all(A, dims) - -Test whether all values along the given dimensions of an array are `true`. - -```jldoctest -julia> A = [true false; true true] -2×2 Array{Bool,2}: - true false - true true - -julia> all(A, 1) -1×2 Array{Bool,2}: - true false - -julia> all(A, 2) -2×1 Array{Bool,2}: - false - true -``` -""" -all(A::AbstractArray, dims) - """ DomainError() @@ -1842,13 +1437,6 @@ The arguments to a function or constructor are outside the valid domain. """ DomainError -""" - acosh(x) - -Compute the inverse hyperbolic cosine of `x`. -""" -acosh - """ IntSet([itr]) @@ -1992,13 +1580,6 @@ values such as `NaN`. """ isless -""" - expm1(x) - -Accurately compute ``e^x-1``. -""" -expm1 - """ showerror(io, e) @@ -2042,13 +1623,6 @@ Perform garbage collection. This should not generally be used. """ gc -""" - minimum!(r, A) - -Compute the minimum value of `A` over the singleton dimensions of `r`, and write results to `r`. -""" -minimum! - """ unsafe_trunc(T, x) @@ -2066,14 +1640,6 @@ it is not a view. """ parent -""" - nextpow(a, x) - -The smallest `a^n` not less than `x`, where `n` is a non-negative integer. `a` must be -greater than 1, and `x` must be greater than 0. -""" -nextpow - """ gc_enable(on::Bool) @@ -2083,20 +1649,6 @@ used only with extreme caution, as it can cause memory use to grow without bound """ gc_enable -""" - atan(x) - -Compute the inverse tangent of `x`, where the output is in radians. -""" -atan - -""" - isinf(f) -> Bool - -Test whether a number is infinite. -""" -isinf - """ secd(x) @@ -2153,21 +1705,6 @@ but deprecated. """ Array -""" - isreal(x) -> Bool - -Test whether `x` or all its elements are numerically equal to some real number. - -```jldoctest -julia> isreal(5.) -true - -julia> isreal([4.; complex(0,1)]) -false -``` -""" -isreal - """ issubtype(type1, type2) @@ -2244,13 +1781,6 @@ Test whether a string contains a match of the given regular expression. """ ismatch -""" - exp(x) - -Compute ``e^x``. -""" -exp - """ matchall(r::Regex, s::AbstractString[, overlap::Bool=false]) -> Vector{AbstractString} @@ -2300,63 +1830,6 @@ the integrity and correctness of data read from `stream`. """ deserialize -""" - first(coll) - -Get the first element of an iterable collection. Returns the start point of a -`Range` even if it is empty. - -```jldoctest -julia> first(2:2:10) -2 - -julia> first([1; 2; 3; 4]) -1 -``` -""" -first - -""" - median!(v) - -Like [`median`](@ref), but may overwrite the input vector. -""" -median! - -""" - cumprod!(B, A, [dim]) - -Cumulative product of `A` along a dimension, storing the result in `B`. The dimension defaults to 1. -""" -cumprod! - -""" - rethrow([e]) - -Throw an object without changing the current exception backtrace. The default argument is -the current exception (if called within a `catch` block). -""" -rethrow - -""" - !(x) - -Boolean not. - -```jldoctest -julia> !true -false - -julia> !false -true - -julia> ![true false true] -1×3 Array{Bool,2}: - false true false -``` -""" -Base.:(!) - """ length(collection) -> Integer @@ -2494,20 +1967,6 @@ Determine whether `x` is of the given `type`. """ isa -""" - catch_backtrace() - -Get the backtrace of the current exception, for use within `catch` blocks. -""" -catch_backtrace - -""" - cos(x) - -Compute cosine of `x`, where `x` is in radians. -""" -cos - """ done(iter, state) -> Bool @@ -2707,20 +2166,6 @@ Return `true` if `A` is a subset of or equal to `S`. """ issubset -""" - zero(x) - -Get the additive identity element for the type of `x` (`x` can also specify the type itself). -""" -zero - -""" - any(A, dims) - -Test whether any values along the given dimensions of an array are `true`. -""" -any(::AbstractArray,dims) - """ zeros([A::AbstractArray,] [T=eltype(A)::Type,] [dims=size(A)::Tuple]) @@ -2849,13 +2294,6 @@ string does not contain a valid number. """ tryparse -""" - all!(r, A) - -Test whether all values in `A` along the singleton dimensions of `r` are `true`, and write results to `r`. -""" -all! - """ exit([code]) @@ -2935,14 +2373,6 @@ for sets of arbitrary objects. """ Set -""" - erf(x) - -Compute the error function of `x`, defined by ``\\frac{2}{\\sqrt{\\pi}} \\int_0^x e^{-t^2} dt`` -for arbitrary complex `x`. -""" -erf - """ signed(x) @@ -3034,22 +2464,3 @@ Compute the Dawson function (scaled imaginary error function) of `x`, defined by ``\\frac{\\sqrt{\\pi}}{2} e^{-x^2} \\operatorname{erfi}(x)``. """ dawson - -""" - xor(x, y) - ⊻(x, y) - -Bitwise exclusive or of `x` and `y`. The infix operation -`a ⊻ b` is a synonym for `xor(a,b)`, and -`⊻` can be typed by tab-completing `\\xor` -or `\\veebar` in the Julia REPL. - -```jldoctest -julia> [true; true; false] ⊻ [true; false; false] -3-element Array{Bool,1}: - false - true - false -``` -""" -Base.xor(x, y) diff --git a/base/error.jl b/base/error.jl index 6e9e6cac867c96..6f534f84a83c02 100644 --- a/base/error.jl +++ b/base/error.jl @@ -21,16 +21,38 @@ error(s::AbstractString) = throw(ErrorException(s)) error(s...) = throw(ErrorException(Main.Base.string(s...))) +""" + rethrow([e]) + +Throw an object without changing the current exception backtrace. The default argument is +the current exception (if called within a `catch` block). +""" rethrow() = ccall(:jl_rethrow, Bottom, ()) rethrow(e) = ccall(:jl_rethrow_other, Bottom, (Any,), e) + +""" + backtrace() + +Get a backtrace object for the current program point. +""" backtrace() = ccall(:jl_backtrace_from_here, Array{Ptr{Void},1}, (Int32,), false) + +""" + catch_backtrace() + +Get the backtrace of the current exception, for use within `catch` blocks. +""" catch_backtrace() = ccall(:jl_get_backtrace, Array{Ptr{Void},1}, ()) ## keyword arg lowering generates calls to this ## kwerr(kw, args...) = throw(MethodError(typeof(args[1]).name.mt.kwsorter, (kw,args...))) ## system error handling ## +""" + systemerror(sysfunc, iftrue) +Raises a `SystemError` for `errno` with the descriptive string `sysfunc` if `iftrue` is `true` +""" systemerror(p, b::Bool; extrainfo=nothing) = b ? throw(Main.Base.SystemError(string(p), Libc.errno(), extrainfo)) : nothing ## assertion functions and macros ## diff --git a/base/float.jl b/base/float.jl index b89ec91e7c9093..2e8f624d125250 100644 --- a/base/float.jl +++ b/base/float.jl @@ -517,11 +517,29 @@ isnan(x::AbstractFloat) = x != x isnan(x::Float16) = reinterpret(UInt16,x)&0x7fff > 0x7c00 isnan(x::Real) = false +""" + isfinite(f) -> Bool + +Test whether a number is finite. + +```jldoctest +julia> isfinite(5) +true + +julia> isfinite(NaN32) +false +``` +""" isfinite(x::AbstractFloat) = x - x == 0 isfinite(x::Float16) = reinterpret(UInt16,x)&0x7c00 != 0x7c00 isfinite(x::Real) = decompose(x)[3] != 0 isfinite(x::Integer) = true +""" + isinf(f) -> Bool + +Test whether a number is infinite. +""" isinf(x::Real) = !isnan(x) & !isfinite(x) ## hashing small, built-in numeric types ## diff --git a/base/intfuncs.jl b/base/intfuncs.jl index bdef46e9e9e11c..309516af6daa13 100644 --- a/base/intfuncs.jl +++ b/base/intfuncs.jl @@ -274,7 +274,12 @@ false """ ispow2(x::Integer) = x > 0 && count_ones(x) == 1 -# smallest a^n >= x, with integer n +""" + nextpow(a, x) + +The smallest `a^n` not less than `x`, where `n` is a non-negative integer. `a` must be +greater than 1, and `x` must be greater than 0. +""" function nextpow(a::Real, x::Real) (a <= 1 || x <= 0) && throw(DomainError()) x <= 1 && return one(a) @@ -283,7 +288,13 @@ function nextpow(a::Real, x::Real) # guard against roundoff error, e.g., with a=5 and x=125 p >= x ? p : a^n end -# largest a^n <= x, with integer n + +""" + prevpow(a, x) + +The largest `a^n` not greater than `x`, where `n` is a non-negative integer. +`a` must be greater than 1, and `x` must not be less than 1. +""" function prevpow(a::Real, x::Real) (a <= 1 || x < 1) && throw(DomainError()) n = floor(Integer,log(a, x)) diff --git a/base/linalg/eigen.jl b/base/linalg/eigen.jl index 1a91f491a6943f..857ca0891c6515 100644 --- a/base/linalg/eigen.jl +++ b/base/linalg/eigen.jl @@ -25,6 +25,12 @@ end isposdef(A::Union{Eigen,GeneralizedEigen}) = isreal(A.values) && all(x -> x > 0, A.values) +""" + eigfact!(A, [B]) + +Same as [`eigfact`](@ref), but saves space by overwriting the input `A` (and +`B`), instead of creating a copy. +""" function eigfact!{T<:BlasReal}(A::StridedMatrix{T}; permute::Bool=true, scale::Bool=true) n = size(A, 2) n == 0 && return Eigen(zeros(T, 0), zeros(T, 0, 0)) diff --git a/base/math.jl b/base/math.jl index 3a66be8ba45dd5..af344fabc8879c 100644 --- a/base/math.jl +++ b/base/math.jl @@ -193,6 +193,69 @@ const libm = Base.libm_name const openspecfun = "libopenspecfun" # functions with no domain error +""" + sinh(x) + +Compute hyperbolic sine of `x`. +""" +sinh(x) + +""" + cosh(x) + +Compute hyperbolic cosine of `x`. +""" +cosh(x) + +""" + tanh(x) + +Compute hyperbolic tangent of `x`. +""" +tanh(x) + +""" + atan(x) + +Compute the inverse tangent of `x`, where the output is in radians. +""" +atan(x) + +""" + asinh(x) + +Compute the inverse hyperbolic sine of `x`. +""" +asinh(x) + +""" + exp(x) + +Compute ``e^x``. +""" +exp(x) + +""" + erf(x) + +Compute the error function of `x`, defined by ``\\frac{2}{\\sqrt{\\pi}} \\int_0^x e^{-t^2} dt`` +for arbitrary complex `x`. +""" +erf(x) + +""" + erfc(x) + +Compute the complementary error function of `x`, defined by ``1 - \\operatorname{erf}(x)``. +""" +erfc(x) + +""" + expm1(x) + +Accurately compute ``e^x-1``. +""" +expm1(x) for f in (:cbrt, :sinh, :cosh, :tanh, :atan, :asinh, :exp, :erf, :erfc, :exp2, :expm1) @eval begin ($f)(x::Float64) = ccall(($(string(f)),libm), Float64, (Float64,), x) @@ -257,6 +320,106 @@ exp10(x::Integer) = exp10(float(x)) @inline nan_dom_err(f, x) = isnan(f) & !isnan(x) ? throw(DomainError()) : f # functions that return NaN on non-NaN argument for domain error +""" + sin(x) + +Compute sine of `x`, where `x` is in radians. +""" +sin(x) + +""" + cos(x) + +Compute cosine of `x`, where `x` is in radians. +""" +cos(x) + +""" + tan(x) + +Compute tangent of `x`, where `x` is in radians. +""" +tan(x) + +""" + asin(x) + +Compute the inverse sine of `x`, where the output is in radians. +""" +asin(x) + +""" + acos(x) + +Compute the inverse cosine of `x`, where the output is in radians +""" +acos(x) + +""" + acosh(x) + +Compute the inverse hyperbolic cosine of `x`. +""" +acosh(x) + +""" + atanh(x) + +Compute the inverse hyperbolic tangent of `x`. +""" +atanh(x) + +""" + log(x) + +Compute the natural logarithm of `x`. Throws [`DomainError`](@ref) for negative `Real` arguments. +Use complex negative arguments to obtain complex results. + +There is an experimental variant in the `Base.Math.JuliaLibm` module, which is typically +faster and more accurate. +""" +log(x) + +""" + log2(x) + +Compute the logarithm of `x` to base 2. Throws [`DomainError`](@ref) for negative `Real` arguments. + +```jldoctest +julia> log2(4) +2.0 + +julia> log2(10) +3.321928094887362 +``` +""" +log2(x) + +""" + log10(x) + +Compute the logarithm of `x` to base 10. +Throws [`DomainError`](@ref) for negative `Real` arguments. + +```jldoctest +julia> log10(100) +2.0 + +julia> log10(2) +0.3010299956639812 +``` +""" +log10(x) + +""" + log1p(x) + +Accurate natural logarithm of `1+x`. Throws [`DomainError`](@ref) for `Real` arguments less than -1. + +There is an experimental variant in the `Base.Math.JuliaLibm` module, which is typically +faster and more accurate. +""" +log1p(x) for f in (:sin, :cos, :tan, :asin, :acos, :acosh, :atanh, :log, :log2, :log10, :lgamma, :log1p) @eval begin diff --git a/base/multidimensional.jl b/base/multidimensional.jl index eeeb92463b013e..18dcefecabc7e1 100644 --- a/base/multidimensional.jl +++ b/base/multidimensional.jl @@ -529,6 +529,12 @@ function accumulate_pairwise{T}(op, v::AbstractVector{T}) return accumulate_pairwise!(op, out, v) end +""" + cumsum!(B, A, [dim]) + +Cumulative sum of `A` along a dimension, storing the result in `B`. The dimension defaults +to 1. +""" function cumsum!(out, v::AbstractVector, axis::Integer=1) # for types prone to numerical stability issues, we want # accumulate_pairwise. @@ -594,6 +600,12 @@ julia> cumprod(a,2) ``` """ cumprod(A::AbstractArray, axis::Integer=1) = accumulate(*, A, axis) + +""" + cumprod!(B, A, [dim]) + +Cumulative product of `A` along a dimension, storing the result in `B`. The dimension defaults to 1. +""" cumprod!(B, A, axis::Integer=1) = accumulate!(*, B, A, axis) """ diff --git a/base/number.jl b/base/number.jl index 9ed1f47487331e..8d5efb5ce7c336 100644 --- a/base/number.jl +++ b/base/number.jl @@ -1,7 +1,19 @@ # This file is a part of Julia. License is MIT: http://julialang.org/license ## generic operations on numbers ## +""" + isinteger(x) -> Bool + +Test whether `x` or all its elements are numerically equal to some integer. + +```jldoctest +julia> isinteger(4.0) +true +julia> isinteger([1; 2; 5.5]) +false +``` +""" isinteger(x::Integer) = true """ @@ -72,7 +84,19 @@ sign(x::Number) = x == 0 ? x/abs(one(x)) : x/abs(x) sign(x::Real) = ifelse(x < 0, oftype(x,-1), ifelse(x > 0, one(x), x)) sign(x::Unsigned) = ifelse(x > 0, one(x), x) abs(x::Real) = ifelse(signbit(x), -x, x) + +""" + abs2(x) + +Squared absolute value of `x`. +""" abs2(x::Real) = x*x + +""" + flipsign(x, y) + +Return `x` with its sign flipped if `y` is negative. For example `abs(x) = flipsign(x,x)`. +""" flipsign(x::Real, y::Real) = ifelse(signbit(y), -x, x) copysign(x::Real, y::Real) = ifelse(signbit(x)!=signbit(y), -x, x) @@ -102,8 +126,20 @@ in(x::Number, y::Number) = x == y map(f, x::Number, ys::Number...) = f(x, ys...) +""" + zero(x) + +Get the additive identity element for the type of `x` (`x` can also specify the type itself). +""" zero(x::Number) = oftype(x,0) zero{T<:Number}(::Type{T}) = convert(T,0) + +""" + one(x) + +Get the multiplicative identity element for the type of `x` (`x` can also specify the type +itself). For matrices, returns an identity matrix of the appropriate size and type. +""" one(x::Number) = oftype(x,1) one{T<:Number}(::Type{T}) = convert(T,1) diff --git a/base/promotion.jl b/base/promotion.jl index 7edd37d3090561..e092fdfa0c4702 100644 --- a/base/promotion.jl +++ b/base/promotion.jl @@ -130,13 +130,22 @@ promote_type{T}(::Type{T}, ::Type{T}) = (@_pure_meta; T) promote_type{T}(::Type{T}, ::Type{Bottom}) = (@_pure_meta; T) promote_type{T}(::Type{Bottom}, ::Type{T}) = (@_pure_meta; T) -# Try promote_rule in both orders. Typically only one is defined, -# and there is a fallback returning Bottom below, so the common case is -# promote_type(T, S) => -# promote_result(T, S, result, Bottom) => -# typejoin(result, Bottom) => result +""" + promote_type(type1, type2) + +Determine a type big enough to hold values of each argument type without loss, whenever +possible. In some cases, where no type exists to which both types can be promoted +losslessly, some loss is tolerated; for example, `promote_type(Int64,Float64)` returns +`Float64` even though strictly, not all `Int64` values can be represented exactly as +`Float64` values. +""" function promote_type{T,S}(::Type{T}, ::Type{S}) @_pure_meta + # Try promote_rule in both orders. Typically only one is defined, + # and there is a fallback returning Bottom below, so the common case is + # promote_type(T, S) => + # promote_result(T, S, result, Bottom) => + # typejoin(result, Bottom) => result promote_result(T, S, promote_rule(T,S), promote_rule(S,T)) end @@ -191,6 +200,12 @@ promote_to_supertype{T<:Number,S<:Number}(::Type{T}, ::Type{S}, ::Type) = *(x::Number, y::Number) = *(promote(x,y)...) -(x::Number, y::Number) = -(promote(x,y)...) /(x::Number, y::Number) = /(promote(x,y)...) + +""" + ^(x, y) + +Exponentiation operator. +""" ^(x::Number, y::Number) = ^(promote(x,y)...) fma(x::Number, y::Number, z::Number) = fma(promote(x,y,z)...) diff --git a/base/rational.jl b/base/rational.jl index 3304247d9783e3..95d2a5d91c5907 100644 --- a/base/rational.jl +++ b/base/rational.jl @@ -19,6 +19,11 @@ function divgcd(x::Integer,y::Integer) div(x,g), div(y,g) end +""" + //(num, den) + +Divide two integers or rational numbers, giving a `Rational` result. +""" //(n::Integer, d::Integer ) = Rational(n,d) function //(x::Rational, y::Integer ) diff --git a/base/reducedim.jl b/base/reducedim.jl index c0599cd3680e42..cb92311655f3ba 100644 --- a/base/reducedim.jl +++ b/base/reducedim.jl @@ -277,6 +277,158 @@ reducedim(op, A::AbstractArray, region) = mapreducedim(identity, op, A, region) ##### Specific reduction functions ##### +""" + sum(A, dims) + +Sum elements of an array over the given dimensions. + +```jldoctest +julia> A = [1 2; 3 4] +2×2 Array{Int64,2}: + 1 2 + 3 4 + +julia> sum(A, 1) +1×2 Array{Int64,2}: + 4 6 + +julia> sum(A, 2) +2×1 Array{Int64,2}: + 3 + 7 +``` +""" +sum(A, dims) + +""" + sum!(r, A) + +Sum elements of `A` over the singleton dimensions of `r`, and write results to `r`. +""" +sum!(r, A) + +""" + prod(A, dims) + +Multiply elements of an array over the given dimensions. + +```jldoctest +julia> A = [1 2; 3 4] +2×2 Array{Int64,2}: + 1 2 + 3 4 + +julia> prod(A, 1) +1×2 Array{Int64,2}: + 3 8 + +julia> prod(A, 2) +2×1 Array{Int64,2}: + 2 + 12 +``` +""" +prod(A, dims) + +""" + prod!(r, A) + +Multiply elements of `A` over the singleton dimensions of `r`, and write results to `r`. +""" +prod!(r, A) + +""" + maximum(A, dims) + +Compute the maximum value of an array over the given dimensions. See also the +[`max(a,b)`](@ref) function to take the maximum of two or more arguments, +which can be applied elementwise to arrays via `max.(a,b)`. +""" +maximum(A, dims) + +""" + maximum!(r, A) + +Compute the maximum value of `A` over the singleton dimensions of `r`, and write results to `r`. +""" +maximum!(r, A) + +""" + minimum(A, dims) + +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)`. + +```jldoctest +julia> A = [1 2; 3 4] +2×2 Array{Int64,2}: + 1 2 + 3 4 + +julia> minimum(A, 1) +1×2 Array{Int64,2}: + 1 2 + +julia> minimum(A, 2) +2×1 Array{Int64,2}: + 1 + 3 +``` +""" +minimum(A, dims) + +""" + minimum!(r, A) + +Compute the minimum value of `A` over the singleton dimensions of `r`, and write results to `r`. +""" +minimum!(r, A) + +""" + all(A, dims) + +Test whether all values along the given dimensions of an array are `true`. + +```jldoctest +julia> A = [true false; true true] +2×2 Array{Bool,2}: + true false + true true + +julia> all(A, 1) +1×2 Array{Bool,2}: + true false + +julia> all(A, 2) +2×1 Array{Bool,2}: + false + true +``` +""" +all(A::AbstractArray, dims) + +""" + all!(r, A) + +Test whether all values in `A` along the singleton dimensions of `r` are `true`, and write results to `r`. +""" +all!(r, A) + +""" + any(A, dims) + +Test whether any values along the given dimensions of an array are `true`. +""" +any(::AbstractArray,dims) + +""" + any!(r, A) + +Test whether any values in `A` along the singleton dimensions of `r` are `true`, and write +results to `r`. +""" +any!(r, A) for (fname, op) in [(:sum, :+), (:prod, :*), (:maximum, :scalarmax), (:minimum, :scalarmin), diff --git a/base/statistics.jl b/base/statistics.jl index e4bc2f1c462afe..7bc582aaf99baa 100644 --- a/base/statistics.jl +++ b/base/statistics.jl @@ -561,6 +561,11 @@ julia> middle(a) """ middle(a::AbstractArray) = ((v1, v2) = extrema(a); middle(v1, v2)) +""" + median!(v) + +Like [`median`](@ref), but may overwrite the input vector. +""" function median!{T}(v::AbstractVector{T}) isempty(v) && throw(ArgumentError("median of an empty array is undefined, $(repr(v))")) if T<:AbstractFloat diff --git a/doc/src/stdlib/math.md b/doc/src/stdlib/math.md index e5596791125572..98d54519037066 100644 --- a/doc/src/stdlib/math.md +++ b/doc/src/stdlib/math.md @@ -9,7 +9,7 @@ Base.:-(::Any, ::Any) Base.:*(::Any, ::Any...) Base.:(/) Base.:\(::Any, ::Any) -Base.:^(::Any, ::Any) +Base.:^(::Number, ::Number) Base.fma Base.muladd Base.div