Movatterモバイル変換


[0]ホーム

URL:


GitHub

Mathematics

Mathematical Operators

Base.:-Method
-(x)

Unary minus operator.

See also:abs,flipsign.

Examples

julia> -1-1julia> -(2)-2julia> -[1 2; 3 4]2×2 Matrix{Int64}: -1  -2 -3  -4julia> -(true)  # promotes to Int-1julia> -(0x003)0xfffd
source
Base.:+Function
dt::Date + t::Time -> DateTime

The addition of aDate with aTime produces aDateTime. The hour, minute, second, and millisecond parts of theTime are used along with the year, month, and day of theDate to create the newDateTime. Non-zero microseconds or nanoseconds in theTime type will result in anInexactError being thrown.

+(x, y...)

Addition operator.

Infixx+y+z+... calls this function with all arguments, i.e.+(x, y, z, ...), which by default then calls(x+y) + z + ... starting from the left.

Note that overflow is possible for most integer types, including the defaultInt, when adding large numbers.

Examples

julia> 1 + 20 + 425julia> +(1, 20, 4)25julia> [1,2] + [3,4]2-element Vector{Int64}: 4 6julia> typemax(Int) + 1 < 0true
source
Base.:-Method
-(x, y)

Subtraction operator.

Examples

julia> 2 - 3-1julia> -(2, 4.5)-2.5
source
Base.:*Method
*(x, y...)

Multiplication operator.

Infixx*y*z*... calls this function with all arguments, i.e.*(x, y, z, ...), which by default then calls(x*y) * z * ... starting from the left.

Juxtaposition such as2pi also calls*(2, pi). Note that this operation has higher precedence than a literal*. Note also that juxtaposition "0x..." (integer zero times a variable whose name starts withx) is forbidden as it clashes with unsigned integer literals:0x01 isa UInt8.

Note that overflow is possible for most integer types, including the defaultInt, when multiplying large numbers.

Examples

julia> 2 * 7 * 8112julia> *(2, 7, 8)112julia> [2 0; 0 3] * [1, 10]  # matrix * vector2-element Vector{Int64}:  2 30julia> 1/2pi, 1/2*pi  # juxtaposition has higher precedence(0.15915494309189535, 1.5707963267948966)julia> x = [1, 2]; x'x  # adjoint vector * vector5
source
Base.:/Function
/(x, y)

Right division operator: multiplication ofx by the inverse ofy on the right.

Gives floating-point results for integer arguments. See÷ for integer division, or// forRational results.

Examples

julia> 1/20.5julia> 4/22.0julia> 4.5/22.25
source
A / B

Matrix right-division:A / B is equivalent to(B' \ A')' where\ is the left-division operator. For square matrices, the resultX is such thatA == X*B.

See also:rdiv!.

Examples

julia> A = Float64[1 4 5; 3 9 2]; B = Float64[1 4 2; 3 4 2; 8 7 1];julia> X = A / B2×3 Matrix{Float64}: -0.65   3.75  -1.2  3.25  -2.75   1.0julia> isapprox(A, X*B)truejulia> isapprox(X, A*pinv(B))true
Base.:\Method
\(x, y)

Left division operator: multiplication ofy by the inverse ofx on the left. Gives floating-point results for integer arguments.

Examples

julia> 3 \ 62.0julia> inv(3) * 62.0julia> A = [4 3; 2 1]; x = [5, 6];julia> A \ x2-element Vector{Float64}:  6.5 -7.0julia> inv(A) * x2-element Vector{Float64}:  6.5 -7.0
source
Base.:^Method
^(x, y)

Exponentiation operator.

Ifx andy are integers, the result may overflow. To enter numbers in scientific notation, useFloat64 literals such as1.2e3 rather than1.2 * 10^3.

Ify is anInt literal (e.g.2 inx^2 or-3 inx^-3), the Julia codex^y is transformed by the compiler toBase.literal_pow(^, x, Val(y)), to enable compile-time specialization on the value of the exponent. (As a default fallback we haveBase.literal_pow(^, x, Val(y)) = ^(x,y), where usually^ == Base.^ unless^ has been defined in the calling namespace.) Ify is a negative integer literal, thenBase.literal_pow transforms the operation toinv(x)^-y by default, where-y is positive.

See alsoexp2,<<.

Examples

julia> 3^5243julia> 3^-1  # uses Base.literal_pow0.3333333333333333julia> p = -1;julia> 3^pERROR: DomainError with -1:Cannot raise an integer x to a negative power -1.[...]julia> 3.0^p0.3333333333333333julia> 10^19 > 0  # integer overflowfalsejulia> big(10)^19 == 1e19true
source
Base.fmaFunction
fma(x, y, z)

Computesx*y+z without rounding the intermediate resultx*y. On some systems this is significantly more expensive thanx*y+z.fma is used to improve accuracy in certain algorithms. Seemuladd.

source
Base.muladdFunction
muladd(x, y, z)

Combined multiply-add: computesx*y+z, but allowing the add and multiply to be merged with each other or with surrounding operations for performance. For example, this may be implemented as anfma if the hardware supports it efficiently. The result can be different on different machines and can also be different on the same machine due to constant propagation or other optimizations. Seefma.

Examples

julia> muladd(3, 2, 1)7julia> 3 * 2 + 17
source
muladd(A, y, z)

Combined multiply-add,A*y .+ z, for matrix-matrix or matrix-vector multiplication. The result is always the same size asA*y, butz may be smaller, or a scalar.

Julia 1.6

These methods require Julia 1.6 or later.

Examples

julia> A=[1.0 2.0; 3.0 4.0]; B=[1.0 1.0; 1.0 1.0]; z=[0, 100];julia> muladd(A, B, z)2×2 Matrix{Float64}:   3.0    3.0 107.0  107.0
Base.invMethod
inv(x)

Return the multiplicative inverse ofx, such thatx*inv(x) orinv(x)*x yieldsone(x) (the multiplicative identity) up to roundoff errors.

Ifx is a number, this is essentially the same asone(x)/x, but for some typesinv(x) may be slightly more efficient.

Examples

julia> inv(2)0.5julia> inv(1 + 2im)0.2 - 0.4imjulia> inv(1 + 2im) * (1 + 2im)1.0 + 0.0imjulia> inv(2//3)3//2
Julia 1.2

inv(::Missing) requires at least Julia 1.2.

source
Base.divFunction
div(x, y)÷(x, y)

The quotient from Euclidean (integer) division. Generally equivalent to a mathematical operation x/y without a fractional part.

See also:cld,fld,rem,divrem.

Examples

julia> 9 ÷ 42julia> -5 ÷ 3-1julia> 5.0 ÷ 22.0julia> div.(-5:5, 3)'1×11 adjoint(::Vector{Int64}) with eltype Int64: -1  -1  -1  0  0  0  0  0  1  1  1
source
Base.divMethod
div(x, y, r::RoundingMode=RoundToZero)

The quotient from Euclidean (integer) division. Computesx / y, rounded to an integer according to the rounding moder. In other words, the quantity

round(x / y, r)

without any intermediate rounding.

Julia 1.4

The three-argument method taking aRoundingMode requires Julia 1.4 or later.

See alsofld andcld, which are special cases of this function.

Julia 1.9

RoundFromZero requires at least Julia 1.9.

Examples:

julia> div(4, 3, RoundToZero) # Matches div(4, 3)1julia> div(4, 3, RoundDown) # Matches fld(4, 3)1julia> div(4, 3, RoundUp) # Matches cld(4, 3)2julia> div(5, 2, RoundNearest)2julia> div(5, 2, RoundNearestTiesAway)3julia> div(-5, 2, RoundNearest)-2julia> div(-5, 2, RoundNearestTiesAway)-3julia> div(-5, 2, RoundNearestTiesUp)-2julia> div(4, 3, RoundFromZero)2julia> div(-4, 3, RoundFromZero)-2
source
Base.fldFunction
fld(x, y)

Largest integer less than or equal tox / y. Equivalent todiv(x, y, RoundDown).

See alsodiv,cld,fld1.

Examples

julia> fld(7.3, 5.5)1.0julia> fld.(-5:5, 3)'1×11 adjoint(::Vector{Int64}) with eltype Int64: -2  -2  -1  -1  -1  0  0  0  1  1  1

Becausefld(x, y) implements strictly correct floored rounding based on the true value of floating-point numbers, unintuitive situations can arise. For example:

julia> fld(6.0, 0.1)59.0julia> 6.0 / 0.160.0julia> 6.0 / big(0.1)59.99999999999999666933092612453056361837965690217069245739573412231113406246995

What is happening here is that the true value of the floating-point number written as0.1 is slightly larger than the numerical value 1/10 while6.0 represents the number 6 precisely. Therefore the true value of6.0 / 0.1 is slightly less than 60. When doing division, this is rounded to precisely60.0, butfld(6.0, 0.1) always takes the floor of the true value, so the result is59.0.

source
Base.cldFunction
cld(x, y)

Smallest integer larger than or equal tox / y. Equivalent todiv(x, y, RoundUp).

See alsodiv,fld.

Examples

julia> cld(5.5, 2.2)3.0julia> cld.(-5:5, 3)'1×11 adjoint(::Vector{Int64}) with eltype Int64: -1  -1  -1  0  0  0  1  1  1  2  2
source
Base.modFunction
mod(x::Integer, r::AbstractUnitRange)

Findy in the ranger such that$x ≡ y (mod n)$, wheren = length(r), i.e.y = mod(x - first(r), n) + first(r).

See alsomod1.

Examples

julia> mod(0, Base.OneTo(3))  # mod1(0, 3)3julia> mod(3, 0:2)  # mod(3, 3)0
Julia 1.3

This method requires at least Julia 1.3.

source
mod(x, y)rem(x, y, RoundDown)

The reduction ofx moduloy, or equivalently, the remainder ofx after floored division byy, i.e.x - y*fld(x,y) if computed without intermediate rounding.

The result will have the same sign asy, and magnitude less thanabs(y) (with some exceptions, see note below).

Note

When used with floating point values, the exact result may not be representable by the type, and so rounding error may occur. In particular, if the exact result is very close toy, then it may be rounded toy.

See also:rem,div,fld,mod1,invmod.

julia> mod(8, 3)2julia> mod(9, 3)0julia> mod(8.9, 3)2.9000000000000004julia> mod(eps(), 3)2.220446049250313e-16julia> mod(-eps(), 3)3.0julia> mod.(-5:5, 3)'1×11 adjoint(::Vector{Int64}) with eltype Int64: 1  2  0  1  2  0  1  2  0  1  2
source
rem(x::Integer, T::Type{<:Integer}) -> Tmod(x::Integer, T::Type{<:Integer}) -> T%(x::Integer, T::Type{<:Integer}) -> T

Findy::T such thatxy (mod n), where n is the number of integers representable inT, andy is an integer in[typemin(T),typemax(T)]. IfT can represent any integer (e.g.T == BigInt), then this operation corresponds to a conversion toT.

Examples

julia> x = 129 % Int8-127julia> typeof(x)Int8julia> x = 129 % BigInt129julia> typeof(x)BigInt
source
Base.remFunction
rem(x, y)%(x, y)

Remainder from Euclidean division, returning a value of the same sign asx, and smaller in magnitude thany. This value is always exact.

See also:div,mod,mod1,divrem.

Examples

julia> x = 15; y = 4;julia> x % y3julia> x == div(x, y) * y + rem(x, y)truejulia> rem.(-5:5, 3)'1×11 adjoint(::Vector{Int64}) with eltype Int64: -2  -1  0  -2  -1  0  1  2  0  1  2
source
Base.remMethod
rem(x, y, r::RoundingMode=RoundToZero)

Compute the remainder ofx after integer division byy, with the quotient rounded according to the rounding moder. In other words, the quantity

x - y * round(x / y, r)

without any intermediate rounding.

  • ifr == RoundNearest, then the result is exact, and in the interval$[-|y| / 2, |y| / 2]$. See alsoRoundNearest.

  • ifr == RoundToZero (default), then the result is exact, and in the interval$[0, |y|)$ ifx is positive, or$(-|y|, 0]$ otherwise. See alsoRoundToZero.

  • ifr == RoundDown, then the result is in the interval$[0, y)$ ify is positive, or$(y, 0]$ otherwise. The result may not be exact ifx andy have different signs, andabs(x) < abs(y). See alsoRoundDown.

  • ifr == RoundUp, then the result is in the interval$(-y, 0]$ ify is positive, or$[0, -y)$ otherwise. The result may not be exact ifx andy have the same sign, andabs(x) < abs(y). See alsoRoundUp.

  • ifr == RoundFromZero, then the result is in the interval$(-y, 0]$ ify is positive, or$[0, -y)$ otherwise. The result may not be exact ifx andy have the same sign, andabs(x) < abs(y). See alsoRoundFromZero.

Julia 1.9

RoundFromZero requires at least Julia 1.9.

Examples:

julia> x = 9; y = 4;julia> x % y  # same as rem(x, y)1julia> x ÷ y  # same as div(x, y)2julia> x == div(x, y) * y + rem(x, y)true
source
Base.Math.rem2piFunction
rem2pi(x, r::RoundingMode)

Compute the remainder ofx after integer division by, with the quotient rounded according to the rounding moder. In other words, the quantity

x - 2π*round(x/(2π),r)

without any intermediate rounding. This internally uses a high precision approximation of 2π, and so will give a more accurate result thanrem(x,2π,r)

  • ifr == RoundNearest, then the result is in the interval$[-π, π]$. This will generally be the most accurate result. See alsoRoundNearest.

  • ifr == RoundToZero, then the result is in the interval$[0, 2π]$ ifx is positive,. or$[-2π, 0]$ otherwise. See alsoRoundToZero.

  • ifr == RoundDown, then the result is in the interval$[0, 2π]$. See alsoRoundDown.

  • ifr == RoundUp, then the result is in the interval$[-2π, 0]$. See alsoRoundUp.

Examples

julia> rem2pi(7pi/4, RoundNearest)-0.7853981633974485julia> rem2pi(7pi/4, RoundDown)5.497787143782138
source
Base.Math.mod2piFunction
mod2pi(x)

Modulus after division by, returning in the range$[0,2π)$.

This function computes a floating point representation of the modulus after division by numerically exact, and is therefore not exactly the same asmod(x,2π), which would compute the modulus ofx relative to division by the floating-point number.

Note

Depending on the format of the input value, the closest representable value to 2π may be less than 2π. For example, the expressionmod2pi(2π) will not return0, because the intermediate value of2*π is aFloat64 and2*Float64(π) < 2*big(π). Seerem2pi for more refined control of this behavior.

Examples

julia> mod2pi(9*pi/4)0.7853981633974481
source
Base.divremFunction
divrem(x, y, r::RoundingMode=RoundToZero)

The quotient and remainder from Euclidean division. Equivalent to(div(x, y, r), rem(x, y, r)). Equivalently, with the default value ofr, this call is equivalent to(x ÷ y, x % y).

See also:fldmod,cld.

Examples

julia> divrem(3, 7)(0, 3)julia> divrem(7, 3)(2, 1)
source
Base.fldmodFunction
fldmod(x, y)

The floored quotient and modulus after division. A convenience wrapper fordivrem(x, y, RoundDown). Equivalent to(fld(x, y), mod(x, y)).

See also:fld,cld,fldmod1.

source
Base.fld1Function
fld1(x, y)

Flooring division, returning a value consistent withmod1(x,y)

See alsomod1,fldmod1.

Examples

julia> x = 15; y = 4;julia> fld1(x, y)4julia> x == fld(x, y) * y + mod(x, y)truejulia> x == (fld1(x, y) - 1) * y + mod1(x, y)true
source
Base.mod1Function
mod1(x, y)

Modulus after flooring division, returning a valuer such thatmod(r, y) == mod(x, y) in the range$(0, y]$ for positivey and in the range$[y,0)$ for negativey.

With integer arguments and positivey, this is equal tomod(x, 1:y), and hence natural for 1-based indexing. By comparison,mod(x, y) == mod(x, 0:y-1) is natural for computations with offsets or strides.

See alsomod,fld1,fldmod1.

Examples

julia> mod1(4, 2)2julia> mod1.(-5:5, 3)'1×11 adjoint(::Vector{Int64}) with eltype Int64: 1  2  3  1  2  3  1  2  3  1  2julia> mod1.([-0.1, 0, 0.1, 1, 2, 2.9, 3, 3.1]', 3)1×8 Matrix{Float64}: 2.9  3.0  0.1  1.0  2.0  2.9  3.0  0.1
source
Base.fldmod1Function
fldmod1(x, y)

Return(fld1(x,y), mod1(x,y)).

See alsofld1,mod1.

source
Base.://Function
//(num, den)

Divide two integers or rational numbers, giving aRational result. More generally,// can be used for exact rational division of other numeric types with integer or rational components, such as complex numbers with integer components.

Note that floating-point (AbstractFloat) arguments are not permitted by// (even if the values are rational). The arguments must be subtypes ofInteger,Rational, or composites thereof.

Examples

julia> 3 // 53//5julia> (3 // 5) // (2 // 1)3//10julia> (1+2im) // (3+4im)11//25 + 2//25*imjulia> 1.0 // 2ERROR: MethodError: no method matching //(::Float64, ::Int64)[...]
source
Base.rationalizeFunction
rationalize([T<:Integer=Int,] x; tol::Real=eps(x))

Approximate floating point numberx as aRational number with components of the given integer type. The result will differ fromx by no more thantol.

Examples

julia> rationalize(5.6)28//5julia> a = rationalize(BigInt, 10.3)103//10julia> typeof(numerator(a))BigInt
source
Base.numeratorFunction
numerator(x)

Numerator of the rational representation ofx.

Examples

julia> numerator(2//3)2julia> numerator(4)4
source
Base.denominatorFunction
denominator(x)

Denominator of the rational representation ofx.

Examples

julia> denominator(2//3)3julia> denominator(4)1
source
Base.:<<Function
<<(x, n)

Left bit shift operator,x << n. Forn >= 0, the result isx shifted left byn bits, filling with0s. This is equivalent tox * 2^n. Forn < 0, this is equivalent tox >> -n.

Examples

julia> Int8(3) << 212julia> bitstring(Int8(3))"00000011"julia> bitstring(Int8(12))"00001100"

See also>>,>>>,exp2,ldexp.

source
<<(B::BitVector, n) -> BitVector

Left bit shift operator,B << n. Forn >= 0, the result isB with elements shiftedn positions backwards, filling withfalse values. Ifn < 0, elements are shifted forwards. Equivalent toB >> -n.

Examples

julia> B = BitVector([true, false, true, false, false])5-element BitVector: 1 0 1 0 0julia> B << 15-element BitVector: 0 1 0 0 0julia> B << -15-element BitVector: 0 1 0 1 0
source
Base.:>>Function
>>(x, n)

Right bit shift operator,x >> n. Forn >= 0, the result isx shifted right byn bits, filling with0s ifx >= 0,1s ifx < 0, preserving the sign ofx. This is equivalent tofld(x, 2^n). Forn < 0, this is equivalent tox << -n.

Examples

julia> Int8(13) >> 23julia> bitstring(Int8(13))"00001101"julia> bitstring(Int8(3))"00000011"julia> Int8(-14) >> 2-4julia> bitstring(Int8(-14))"11110010"julia> bitstring(Int8(-4))"11111100"

See also>>>,<<.

source
>>(B::BitVector, n) -> BitVector

Right bit shift operator,B >> n. Forn >= 0, the result isB with elements shiftedn positions forward, filling withfalse values. Ifn < 0, elements are shifted backwards. Equivalent toB << -n.

Examples

julia> B = BitVector([true, false, true, false, false])5-element BitVector: 1 0 1 0 0julia> B >> 15-element BitVector: 0 1 0 1 0julia> B >> -15-element BitVector: 0 1 0 0 0
source
Base.:>>>Function
>>>(x, n)

Unsigned right bit shift operator,x >>> n. Forn >= 0, the result isx shifted right byn bits, filling with0s. Forn < 0, this is equivalent tox << -n.

ForUnsigned integer types, this is equivalent to>>. ForSigned integer types, this is equivalent tosigned(unsigned(x) >> n).

Examples

julia> Int8(-14) >>> 260julia> bitstring(Int8(-14))"11110010"julia> bitstring(Int8(60))"00111100"

BigInts are treated as if having infinite size, so no filling is required and this is equivalent to>>.

See also>>,<<.

source
>>>(B::BitVector, n) -> BitVector

Unsigned right bitshift operator,B >>> n. Equivalent toB >> n. See>> for details and examples.

source
Base.bitrotateFunction
bitrotate(x::Base.BitInteger, k::Integer)

bitrotate(x, k) implements bitwise rotation. It returns the value ofx with its bits rotated leftk times. A negative value ofk will rotate to the right instead.

Julia 1.5

This function requires Julia 1.5 or later.

See also:<<,circshift,BitArray.

julia> bitrotate(UInt8(114), 2)0xc9julia> bitstring(bitrotate(0b01110010, 2))"11001001"julia> bitstring(bitrotate(0b01110010, -2))"10011100"julia> bitstring(bitrotate(0b01110010, 8))"01110010"
source
Base.::Function
:expr

Quote an expressionexpr, returning the abstract syntax tree (AST) ofexpr. The AST may be of typeExpr,Symbol, or a literal value. The syntax:identifier evaluates to aSymbol.

See also:Expr,Symbol,Meta.parse

Examples

julia> expr = :(a = b + 2*x):(a = b + 2x)julia> sym = :some_identifier:some_identifierjulia> value = :0xff0xffjulia> typeof((expr, sym, value))Tuple{Expr, Symbol, UInt8}
source
Base.rangeFunction
range(start, stop, length)range(start, stop; length, step)range(start; length, stop, step)range(;start, length, stop, step)

Construct a specialized array with evenly spaced elements and optimized storage (anAbstractRange) from the arguments. Mathematically a range is uniquely determined by any three ofstart,step,stop andlength. Valid invocations of range are:

  • Callrange with any three ofstart,step,stop,length.
  • Callrange with two ofstart,stop,length. In this casestep will be assumed to be one. If both arguments are Integers, aUnitRange will be returned.
  • Callrange with one ofstop orlength.start andstep will be assumed to be one.

See Extended Help for additional details on the returned type. See alsologrange for logarithmically spaced points.

Examples

julia> range(1, length=100)1:100julia> range(1, stop=100)1:100julia> range(1, step=5, length=100)1:5:496julia> range(1, step=5, stop=100)1:5:96julia> range(1, 10, length=101)1.0:0.09:10.0julia> range(1, 100, step=5)1:5:96julia> range(stop=10, length=5)6:10julia> range(stop=10, step=1, length=5)6:1:10julia> range(start=1, step=1, stop=10)1:1:10julia> range(; length = 10)Base.OneTo(10)julia> range(; stop = 6)Base.OneTo(6)julia> range(; stop = 6.5)1.0:1.0:6.0

Iflength is not specified andstop - start is not an integer multiple ofstep, a range that ends beforestop will be produced.

julia> range(1, 3.5, step=2)1.0:2.0:3.0

Special care is taken to ensure intermediate values are computed rationally. To avoid this induced overhead, see theLinRange constructor.

Julia 1.1

stop as a positional argument requires at least Julia 1.1.

Julia 1.7

The versions without keyword arguments andstart as a keyword argument require at least Julia 1.7.

Julia 1.8

The versions withstop as a sole keyword argument, orlength as a sole keyword argument require at least Julia 1.8.

Extended Help

range will produce aBase.OneTo when the arguments are Integers and

  • Onlylength is provided
  • Onlystop is provided

range will produce aUnitRange when the arguments are Integers and

  • Onlystart andstop are provided
  • Onlylength andstop are provided

AUnitRange is not produced ifstep is provided even if specified as one.

source
Base.OneToType
Base.OneTo(n)

Define anAbstractUnitRange that behaves like1:n, with the added distinction that the lower limit is guaranteed (by the type system) to be 1.

source
Base.StepRangeLenType
StepRangeLen(         ref::R, step::S, len, [offset=1]) where {  R,S}StepRangeLen{T,R,S}(  ref::R, step::S, len, [offset=1]) where {T,R,S}StepRangeLen{T,R,S,L}(ref::R, step::S, len, [offset=1]) where {T,R,S,L}

A ranger wherer[i] produces values of typeT (in the first form,T is deduced automatically), parameterized by areference value, astep, and thelength. By defaultref is the starting valuer[1], but alternatively you can supply it as the value ofr[offset] for some other index1 <= offset <= len. The syntaxa:b ora:b:c, where any ofa,b, orc are floating-point numbers, creates aStepRangeLen.

Julia 1.7

The 4th type parameterL requires at least Julia 1.7.

source
Base.lograngeFunction
logrange(start, stop, length)logrange(start, stop; length)

Construct a specialized array whose elements are spaced logarithmically between the given endpoints. That is, the ratio of successive elements is a constant, calculated from the length.

This is similar togeomspace in Python. UnlikePowerRange in Mathematica, you specify the number of elements not the ratio. Unlikelogspace in Python and Matlab, thestart andstop arguments are always the first and last elements of the result, not powers applied to some base.

Examples

julia> logrange(10, 4000, length=3)3-element Base.LogRange{Float64, Base.TwicePrecision{Float64}}: 10.0, 200.0, 4000.0julia> ans[2] ≈ sqrt(10 * 4000)  # middle element is the geometric meantruejulia> range(10, 40, length=3)[2] ≈ (10 + 40)/2  # arithmetic meantruejulia> logrange(1f0, 32f0, 11)11-element Base.LogRange{Float32, Float64}: 1.0, 1.41421, 2.0, 2.82843, 4.0, 5.65685, 8.0, 11.3137, 16.0, 22.6274, 32.0julia> logrange(1, 1000, length=4) ≈ 10 .^ (0:3)true

See theLogRange type for further details.

See alsorange for linearly spaced points.

Julia 1.11

This function requires at least Julia 1.11.

source
Base.LogRangeType
LogRange{T}(start, stop, len) <: AbstractVector{T}

A range whose elements are spaced logarithmically betweenstart andstop, with spacing controlled bylen. Returned bylogrange.

LikeLinRange, the first and last elements will be exactly those provided, but intermediate values may have small floating-point errors. These are calculated using the logs of the endpoints, which are stored on construction, often in higher precision thanT.

Examples

julia> logrange(1, 4, length=5)5-element Base.LogRange{Float64, Base.TwicePrecision{Float64}}: 1.0, 1.41421, 2.0, 2.82843, 4.0julia> Base.LogRange{Float16}(1, 4, 5)5-element Base.LogRange{Float16, Float64}: 1.0, 1.414, 2.0, 2.828, 4.0julia> logrange(1e-310, 1e-300, 11)[1:2:end]6-element Vector{Float64}: 1.0e-310 9.999999999999974e-309 9.999999999999981e-307 9.999999999999988e-305 9.999999999999994e-303 1.0e-300julia> prevfloat(1e-308, 5) == ans[2]true

Note that integer eltypeT is not allowed. Use for instanceround.(Int, xs), or explicit powers of some integer base:

julia> xs = logrange(1, 512, 4)4-element Base.LogRange{Float64, Base.TwicePrecision{Float64}}: 1.0, 8.0, 64.0, 512.0julia> 2 .^ (0:3:9) |> println[1, 8, 64, 512]
Julia 1.11

This type requires at least Julia 1.11.

source
Base.:==Function
==(x, y)

Generic equality operator. Falls back to===. Should be implemented for all types with a notion of equality, based on the abstract value that an instance represents. For example, all numeric types are compared by numeric value, ignoring type. Strings are compared as sequences of characters, ignoring encoding. Collections of the same type generally compare their key sets, and if those are==, then compare the values for each of those keys, returning true if all such pairs are==. Other properties are typically not taken into account (such as the exact type).

This operator follows IEEE semantics for floating-point numbers:0.0 == -0.0 andNaN != NaN.

The result is of typeBool, except when one of the operands ismissing, in which casemissing is returned (three-valued logic). Collections generally implement three-valued logic akin toall, returning missing if any operands contain missing values and all other pairs are equal. Useisequal or=== to always get aBool result.

Implementation

New numeric types should implement this function for two arguments of the new type, and handle comparison to other types via promotion rules where possible.

isequal falls back to==, so new methods of== will be used by theDict type to compare keys. If your type will be used as a dictionary key, it should therefore also implementhash.

If some type defines==,isequal, andisless then it should also implement< to ensure consistency of comparisons.

source
Base.:!=Function
!=(x, y)≠(x,y)

Not-equals comparison operator. Always gives the opposite answer as==.

Implementation

New types should generally not implement this, and rely on the fallback definition!=(x,y) = !(x==y) instead.

Examples

julia> 3 != 2truejulia> "foo" ≠ "foo"false
source
!=(x)

Create a function that compares its argument tox using!=, i.e. a function equivalent toy -> y != x. The returned function is of typeBase.Fix2{typeof(!=)}, which can be used to implement specialized methods.

Julia 1.2

This functionality requires at least Julia 1.2.

source
Base.:!==Function
!==(x, y)≢(x,y)

Always gives the opposite answer as===.

Examples

julia> a = [1, 2]; b = [1, 2];julia> a ≢ btruejulia> a ≢ afalse
source
Base.:<Function
<(x, y)

Less-than comparison operator. Falls back toisless. Because of the behavior of floating-point NaN values, this operator implements a partial order.

Implementation

New types with a canonical partial order should implement this function for two arguments of the new type. Types with a canonical total order should implementisless instead.

See alsoisunordered.

Examples

julia> 'a' < 'b'truejulia> "abc" < "abd"truejulia> 5 < 3false
source
<(x)

Create a function that compares its argument tox using<, i.e. a function equivalent toy -> y < x. The returned function is of typeBase.Fix2{typeof(<)}, which can be used to implement specialized methods.

Julia 1.2

This functionality requires at least Julia 1.2.

source
Base.:<=Function
<=(x, y)≤(x,y)

Less-than-or-equals comparison operator. Falls back to(x < y) | (x == y).

Examples

julia> 'a' <= 'b'truejulia> 7 ≤ 7 ≤ 9truejulia> "abc" ≤ "abc"truejulia> 5 <= 3false
source
<=(x)

Create a function that compares its argument tox using<=, i.e. a function equivalent toy -> y <= x. The returned function is of typeBase.Fix2{typeof(<=)}, which can be used to implement specialized methods.

Julia 1.2

This functionality requires at least Julia 1.2.

source
Base.:>Function
>(x, y)

Greater-than comparison operator. Falls back toy < x.

Implementation

Generally, new types should implement< instead of this function, and rely on the fallback definition>(x, y) = y < x.

Examples

julia> 'a' > 'b'falsejulia> 7 > 3 > 1truejulia> "abc" > "abd"falsejulia> 5 > 3true
source
>(x)

Create a function that compares its argument tox using>, i.e. a function equivalent toy -> y > x. The returned function is of typeBase.Fix2{typeof(>)}, which can be used to implement specialized methods.

Julia 1.2

This functionality requires at least Julia 1.2.

source
Base.:>=Function
>=(x, y)≥(x,y)

Greater-than-or-equals comparison operator. Falls back toy <= x.

Examples

julia> 'a' >= 'b'falsejulia> 7 ≥ 7 ≥ 3truejulia> "abc" ≥ "abc"truejulia> 5 >= 3true
source
>=(x)

Create a function that compares its argument tox using>=, i.e. a function equivalent toy -> y >= x. The returned function is of typeBase.Fix2{typeof(>=)}, which can be used to implement specialized methods.

Julia 1.2

This functionality requires at least Julia 1.2.

source
Base.cmpFunction
cmp(x,y)

Return -1, 0, or 1 depending on whetherx is less than, equal to, or greater thany, respectively. Uses the total order implemented byisless.

Examples

julia> cmp(1, 2)-1julia> cmp(2, 1)1julia> cmp(2+im, 3-im)ERROR: MethodError: no method matching isless(::Complex{Int64}, ::Complex{Int64})[...]
source
cmp(<, x, y)

Return -1, 0, or 1 depending on whetherx is less than, equal to, or greater thany, respectively. The first argument specifies a less-than comparison function to use.

source
cmp(a::AbstractString, b::AbstractString) -> Int

Compare two strings. Return0 if both strings have the same length and the character at each index is the same in both strings. Return-1 ifa is a prefix ofb, or ifa comes beforeb in alphabetical order. Return1 ifb is a prefix ofa, or ifb comes beforea in alphabetical order (technically, lexicographical order by Unicode code points).

Examples

julia> cmp("abc", "abc")0julia> cmp("ab", "abc")-1julia> cmp("abc", "ab")1julia> cmp("ab", "ac")-1julia> cmp("ac", "ab")1julia> cmp("α", "a")1julia> cmp("b", "β")-1
source
Base.:~Function
~(x)

Bitwise not.

See also:!,&,|.

Examples

julia> ~4-5julia> ~10-11julia> ~truefalse
source
Base.:&Function
x & y

Bitwise and. Implementsthree-valued logic, returningmissing if one operand ismissing and the other istrue. Add parentheses for function application form:(&)(x, y).

See also:|,xor,&&.

Examples

julia> 4 & 100julia> 4 & 124julia> true & missingmissingjulia> false & missingfalse
source
Base.:|Function
x | y

Bitwise or. Implementsthree-valued logic, returningmissing if one operand ismissing and the other isfalse.

See also:&,xor,||.

Examples

julia> 4 | 1014julia> 4 | 15julia> true | missingtruejulia> false | missingmissing
source
Base.xorFunction
xor(x, y)⊻(x, y)

Bitwise exclusive or ofx andy. Implementsthree-valued logic, returningmissing if one of the arguments ismissing.

The infix operationa ⊻ b is a synonym forxor(a,b), and can be typed by tab-completing\xor or\veebar in the Julia REPL.

Examples

julia> xor(true, false)truejulia> xor(true, true)falsejulia> xor(true, missing)missingjulia> false ⊻ falsefalsejulia> [true; true; false] .⊻ [true; false; false]3-element BitVector: 0 1 0
source
Base.nandFunction
nand(x, y)⊼(x, y)

Bitwise nand (not and) ofx andy. Implementsthree-valued logic, returningmissing if one of the arguments ismissing.

The infix operationa ⊼ b is a synonym fornand(a,b), and can be typed by tab-completing\nand or\barwedge in the Julia REPL.

Examples

julia> nand(true, false)truejulia> nand(true, true)falsejulia> nand(true, missing)missingjulia> false ⊼ falsetruejulia> [true; true; false] .⊼ [true; false; false]3-element BitVector: 0 1 1
source
Base.norFunction
nor(x, y)⊽(x, y)

Bitwise nor (not or) ofx andy. Implementsthree-valued logic, returningmissing if one of the arguments ismissing and the other is nottrue.

The infix operationa ⊽ b is a synonym fornor(a,b), and can be typed by tab-completing\nor or\barvee in the Julia REPL.

Examples

julia> nor(true, false)falsejulia> nor(true, true)falsejulia> nor(true, missing)falsejulia> false ⊽ falsetruejulia> false ⊽ missingmissingjulia> [true; true; false] .⊽ [true; false; false]3-element BitVector: 0 0 1
source
Base.:!Function
!(x)

Boolean not. Implementsthree-valued logic, returningmissing ifx ismissing.

See also~ for bitwise not.

Examples

julia> !truefalsejulia> !falsetruejulia> !missingmissingjulia> .![true false true]1×3 BitMatrix: 0  1  0
source
!f::Function

Predicate function negation: when the argument of! is a function, it returns a composed function which computes the boolean negation off.

See also.

Examples

julia> str = "∀ ε > 0, ∃ δ > 0: |x-y| < δ ⇒ |f(x)-f(y)| < ε""∀ ε > 0, ∃ δ > 0: |x-y| < δ ⇒ |f(x)-f(y)| < ε"julia> filter(isletter, str)"εδxyδfxfyε"julia> filter(!isletter, str)"∀  > 0, ∃  > 0: |-| <  ⇒ |()-()| < "
Julia 1.9

Starting with Julia 1.9,!f returns aComposedFunction instead of an anonymous function.

source
&&Keyword
x && y

Short-circuiting boolean AND.

See also&, the ternary operator? :, and the manual section oncontrol flow.

Examples

julia> x = 3;julia> x > 1 && x < 10 && x isa Inttruejulia> x < 0 && error("expected positive x")false
source
||Keyword
x || y

Short-circuiting boolean OR.

See also:|,xor,&&.

Examples

julia> pi < 3 || ℯ < 3truejulia> false || true || println("neither is true!")true
source

Mathematical Functions

Base.isapproxFunction
isapprox(x, y; atol::Real=0, rtol::Real=atol>0 ? 0 : √eps, nans::Bool=false[, norm::Function])

Inexact equality comparison. Two numbers compare equal if their relative distanceor their absolute distance is within tolerance bounds:isapprox returnstrue ifnorm(x-y) <= max(atol, rtol*max(norm(x), norm(y))). The defaultatol (absolute tolerance) is zero and the defaultrtol (relative tolerance) depends on the types ofx andy. The keyword argumentnans determines whether or not NaN values are considered equal (defaults to false).

For real or complex floating-point values, if anatol > 0 is not specified,rtol defaults to the square root ofeps of the type ofx ory, whichever is bigger (least precise). This corresponds to requiring equality of about half of the significant digits. Otherwise, e.g. for integer arguments or if anatol > 0 is supplied,rtol defaults to zero.

Thenorm keyword defaults toabs for numeric(x,y) and toLinearAlgebra.norm for arrays (where an alternativenorm choice is sometimes useful). Whenx andy are arrays, ifnorm(x-y) is not finite (i.e.±Inf orNaN), the comparison falls back to checking whether all elements ofx andy are approximately equal component-wise.

The binary operator is equivalent toisapprox with the default arguments, andx ≉ y is equivalent to!isapprox(x,y).

Note thatx ≈ 0 (i.e., comparing to zero with the default tolerances) is equivalent tox == 0 since the defaultatol is0. In such cases, you should either supply an appropriateatol (or usenorm(x) ≤ atol) or rearrange your code (e.g. usex ≈ y rather thanx - y ≈ 0). It is not possible to pick a nonzeroatol automatically because it depends on the overall scaling (the "units") of your problem: for example, inx - y ≈ 0,atol=1e-9 is an absurdly small tolerance ifx is theradius of the Earth in meters, but an absurdly large tolerance ifx is theradius of a Hydrogen atom in meters.

Julia 1.6

Passing thenorm keyword argument when comparing numeric (non-array) arguments requires Julia 1.6 or later.

Examples

julia> isapprox(0.1, 0.15; atol=0.05)truejulia> isapprox(0.1, 0.15; rtol=0.34)truejulia> isapprox(0.1, 0.15; rtol=0.33)falsejulia> 0.1 + 1e-10 ≈ 0.1truejulia> 1e-10 ≈ 0falsejulia> isapprox(1e-10, 0, atol=1e-8)truejulia> isapprox([10.0^9, 1.0], [10.0^9, 2.0]) # using `norm`true
source
isapprox(x; kwargs...) / ≈(x; kwargs...)

Create a function that compares its argument tox using, i.e. a function equivalent toy -> y ≈ x.

The keyword arguments supported here are the same as those in the 2-argumentisapprox.

Julia 1.5

This method requires Julia 1.5 or later.

source
Base.sinMethod
sin(x)

Compute sine ofx, wherex is in radians.

See alsosind,sinpi,sincos,cis,asin.

Examples

julia> round.(sin.(range(0, 2pi, length=9)'), digits=3)1×9 Matrix{Float64}: 0.0  0.707  1.0  0.707  0.0  -0.707  -1.0  -0.707  -0.0julia> sind(45)0.7071067811865476julia> sinpi(1/4)0.7071067811865475julia> round.(sincos(pi/6), digits=3)(0.5, 0.866)julia> round(cis(pi/6), digits=3)0.866 + 0.5imjulia> round(exp(im*pi/6), digits=3)0.866 + 0.5im
source
Base.cosMethod
cos(x)

Compute cosine ofx, wherex is in radians.

See alsocosd,cospi,sincos,cis.

source
Base.Math.sincosMethod
sincos(x)

Simultaneously compute the sine and cosine ofx, wherex is in radians, returning a tuple(sine, cosine).

See alsocis,sincospi,sincosd.

source
Base.tanMethod
tan(x)

Compute tangent ofx, wherex is in radians.

source
Base.Math.sindFunction
sind(x)

Compute sine ofx, wherex is in degrees. Ifx is a matrix,x needs to be a square matrix.

Julia 1.7

Matrix arguments require Julia 1.7 or later.

source
Base.Math.cosdFunction
cosd(x)

Compute cosine ofx, wherex is in degrees. Ifx is a matrix,x needs to be a square matrix.

Julia 1.7

Matrix arguments require Julia 1.7 or later.

source
Base.Math.tandFunction
tand(x)

Compute tangent ofx, wherex is in degrees. Ifx is a matrix,x needs to be a square matrix.

Julia 1.7

Matrix arguments require Julia 1.7 or later.

source
Base.Math.sincosdFunction
sincosd(x)

Simultaneously compute the sine and cosine ofx, wherex is in degrees.

Julia 1.3

This function requires at least Julia 1.3.

source
Base.Math.sinpiFunction
sinpi(x)

Compute$\sin(\pi x)$ more accurately thansin(pi*x), especially for largex.

See alsosind,cospi,sincospi.

source
Base.Math.cospiFunction
cospi(x)

Compute$\cos(\pi x)$ more accurately thancos(pi*x), especially for largex.

source
Base.Math.tanpiFunction
tanpi(x)

Compute$\tan(\pi x)$ more accurately thantan(pi*x), especially for largex.

Julia 1.10

This function requires at least Julia 1.10.

See alsotand,sinpi,cospi,sincospi.

source
Base.Math.sincospiFunction
sincospi(x)

Simultaneously computesinpi(x) andcospi(x) (the sine and cosine ofπ*x, wherex is in radians), returning a tuple(sine, cosine).

Julia 1.6

This function requires Julia 1.6 or later.

See also:cispi,sincosd,sinpi.

source
Base.sinhMethod
sinh(x)

Compute hyperbolic sine ofx.

source
Base.coshMethod
cosh(x)

Compute hyperbolic cosine ofx.

source
Base.tanhMethod
tanh(x)

Compute hyperbolic tangent ofx.

See alsotan,atanh.

Examples

julia> tanh.(-3:3f0)  # Here 3f0 isa Float327-element Vector{Float32}: -0.9950548 -0.9640276 -0.7615942  0.0  0.7615942  0.9640276  0.9950548julia> tan.(im .* (1:3))3-element Vector{ComplexF64}: 0.0 + 0.7615941559557649im 0.0 + 0.9640275800758169im 0.0 + 0.9950547536867306im
source
Base.asinMethod
asin(x)

Compute the inverse sine ofx, where the output is in radians.

See alsoasind for output in degrees.

Examples

julia> asin.((0, 1/2, 1))(0.0, 0.5235987755982989, 1.5707963267948966)julia> asind.((0, 1/2, 1))(0.0, 30.000000000000004, 90.0)
source
Base.acosMethod
acos(x)

Compute the inverse cosine ofx, where the output is in radians

source
Base.atanMethod
atan(y)atan(y, x)

Compute the inverse tangent ofy ory/x, respectively.

For one real argument, this is the angle in radians between the positivex-axis and the point (1,y), returning a value in the interval$[-\pi/2, \pi/2]$.

For two arguments, this is the angle in radians between the positivex-axis and the point (x,y), returning a value in the interval$[-\pi, \pi]$. This corresponds to a standardatan2 function. Note that by conventionatan(0.0,x) is defined as$\pi$ andatan(-0.0,x) is defined as$-\pi$ whenx < 0.

See alsoatand for degrees.

Examples

julia> rad2deg(atan(-1/√3))-30.000000000000004julia> rad2deg(atan(-1, √3))-30.000000000000004julia> rad2deg(atan(1, -√3))150.0
source
Base.Math.asindFunction
asind(x)

Compute the inverse sine ofx, where the output is in degrees. Ifx is a matrix,x needs to be a square matrix.

Julia 1.7

Matrix arguments require Julia 1.7 or later.

source
Base.Math.acosdFunction
acosd(x)

Compute the inverse cosine ofx, where the output is in degrees. Ifx is a matrix,x needs to be a square matrix.

Julia 1.7

Matrix arguments require Julia 1.7 or later.

source
Base.Math.atandFunction
atand(y)atand(y,x)

Compute the inverse tangent ofy ory/x, respectively, where the output is in degrees.

Julia 1.7

The one-argument method supports square matrix arguments as of Julia 1.7.

source
Base.Math.secMethod
sec(x)

Compute the secant ofx, wherex is in radians.

source
Base.Math.cscMethod
csc(x)

Compute the cosecant ofx, wherex is in radians.

source
Base.Math.cotMethod
cot(x)

Compute the cotangent ofx, wherex is in radians.

source
Base.Math.secdFunction
secd(x)

Compute the secant ofx, wherex is in degrees.

source
Base.Math.cscdFunction
cscd(x)

Compute the cosecant ofx, wherex is in degrees.

source
Base.Math.cotdFunction
cotd(x)

Compute the cotangent ofx, wherex is in degrees.

source
Base.Math.asecMethod
asec(x)

Compute the inverse secant ofx, where the output is in radians.

source
Base.Math.acscMethod
acsc(x)

Compute the inverse cosecant ofx, where the output is in radians.

source
Base.Math.acotMethod
acot(x)

Compute the inverse cotangent ofx, where the output is in radians.

source
Base.Math.asecdFunction
asecd(x)

Compute the inverse secant ofx, where the output is in degrees. Ifx is a matrix,x needs to be a square matrix.

Julia 1.7

Matrix arguments require Julia 1.7 or later.

source
Base.Math.acscdFunction
acscd(x)

Compute the inverse cosecant ofx, where the output is in degrees. Ifx is a matrix,x needs to be a square matrix.

Julia 1.7

Matrix arguments require Julia 1.7 or later.

source
Base.Math.acotdFunction
acotd(x)

Compute the inverse cotangent ofx, where the output is in degrees. Ifx is a matrix,x needs to be a square matrix.

Julia 1.7

Matrix arguments require Julia 1.7 or later.

source
Base.Math.sechMethod
sech(x)

Compute the hyperbolic secant ofx.

source
Base.Math.cschMethod
csch(x)

Compute the hyperbolic cosecant ofx.

source
Base.Math.cothMethod
coth(x)

Compute the hyperbolic cotangent ofx.

source
Base.asinhMethod
asinh(x)

Compute the inverse hyperbolic sine ofx.

source
Base.acoshMethod
acosh(x)

Compute the inverse hyperbolic cosine ofx.

source
Base.atanhMethod
atanh(x)

Compute the inverse hyperbolic tangent ofx.

source
Base.Math.asechMethod
asech(x)

Compute the inverse hyperbolic secant ofx.

source
Base.Math.acschMethod
acsch(x)

Compute the inverse hyperbolic cosecant ofx.

source
Base.Math.acothMethod
acoth(x)

Compute the inverse hyperbolic cotangent ofx.

source
Base.Math.sincFunction
sinc(x)

Compute normalized sinc function$\operatorname{sinc}(x) = \sin(\pi x) / (\pi x)$ if$x \neq 0$, and$1$ if$x = 0$.

See alsocosc, its derivative.

source
Base.Math.coscFunction
cosc(x)

Compute$\cos(\pi x) / x - \sin(\pi x) / (\pi x^2)$ if$x \neq 0$, and$0$ if$x = 0$. This is the derivative ofsinc(x).

See alsosinc.

source
Base.Math.deg2radFunction
deg2rad(x)

Convertx from degrees to radians.

See alsorad2deg,sind,pi.

Examples

julia> deg2rad(90)1.5707963267948966
source
Base.Math.rad2degFunction
rad2deg(x)

Convertx from radians to degrees.

See alsodeg2rad.

Examples

julia> rad2deg(pi)180.0
source
Base.Math.hypotFunction
hypot(x, y)

Compute the hypotenuse$\sqrt{|x|^2+|y|^2}$ avoiding overflow and underflow.

This code is an implementation of the algorithm described in: An Improved Algorithm forhypot(a,b) by Carlos F. Borges The article is available online at arXiv at the link https://arxiv.org/abs/1904.09481

hypot(x...)

Compute the hypotenuse$\sqrt{\sum |x_i|^2}$ avoiding overflow and underflow.

See alsonorm in theLinearAlgebra standard library.

Examples

julia> a = Int64(10)^10;julia> hypot(a, a)1.4142135623730951e10julia> √(a^2 + a^2) # a^2 overflowsERROR: DomainError with -2.914184810805068e18:sqrt was called with a negative real argument but will only return a complex result if called with a complex argument. Try sqrt(Complex(x)).Stacktrace:[...]julia> hypot(3, 4im)5.0julia> hypot(-5.7)5.7julia> hypot(3, 4im, 12.0)13.0julia> using LinearAlgebrajulia> norm([a, a, a, a]) == hypot(a, a, a, a)true
source
Base.logMethod
log(x)

Compute the natural logarithm ofx.

ThrowsDomainError for negativeReal arguments. Use complex arguments to obtain complex results. Has a branch cut along the negative real axis, for which-0.0im is taken to be below the axis.

See also,log1p,log2,log10.

Examples

julia> log(2)0.6931471805599453julia> log(-3)ERROR: DomainError with -3.0:log was called with a negative real argument but will only return a complex result if called with a complex argument. Try log(Complex(x)).Stacktrace: [1] throw_complex_domainerror(::Symbol, ::Float64) at ./math.jl:31[...]julia> log(-3 + 0im)1.0986122886681098 + 3.141592653589793imjulia> log(-3 - 0.0im)1.0986122886681098 - 3.141592653589793imjulia> log.(exp.(-1:1))3-element Vector{Float64}: -1.0  0.0  1.0
source
Base.logMethod
log(b,x)

Compute the baseb logarithm ofx. ThrowsDomainError for negativeReal arguments.

Examples

julia> log(4,8)1.5julia> log(4,2)0.5julia> log(-2, 3)ERROR: DomainError with -2.0:log was called with a negative real argument but will only return a complex result if called with a complex argument. Try log(Complex(x)).Stacktrace: [1] throw_complex_domainerror(::Symbol, ::Float64) at ./math.jl:31[...]julia> log(2, -3)ERROR: DomainError with -3.0:log was called with a negative real argument but will only return a complex result if called with a complex argument. Try log(Complex(x)).Stacktrace: [1] throw_complex_domainerror(::Symbol, ::Float64) at ./math.jl:31[...]
Note

Ifb is a power of 2 or 10,log2 orlog10 should be used, as these will typically be faster and more accurate. For example,

julia> log(100,1000000)2.9999999999999996julia> log10(1000000)/23.0
source
Base.log2Function
log2(x)

Compute the logarithm ofx to base 2. ThrowsDomainError for negativeReal arguments.

See also:exp2,ldexp,ispow2.

Examples

julia> log2(4)2.0julia> log2(10)3.321928094887362julia> log2(-2)ERROR: DomainError with -2.0:log2 was called with a negative real argument but will only return a complex result if called with a complex argument. Try log2(Complex(x)).Stacktrace: [1] throw_complex_domainerror(f::Symbol, x::Float64) at ./math.jl:31[...]julia> log2.(2.0 .^ (-1:1))3-element Vector{Float64}: -1.0  0.0  1.0
source
Base.log10Function
log10(x)

Compute the logarithm ofx to base 10. ThrowsDomainError for negativeReal arguments.

Examples

julia> log10(100)2.0julia> log10(2)0.3010299956639812julia> log10(-2)ERROR: DomainError with -2.0:log10 was called with a negative real argument but will only return a complex result if called with a complex argument. Try log10(Complex(x)).Stacktrace: [1] throw_complex_domainerror(f::Symbol, x::Float64) at ./math.jl:31[...]
source
Base.log1pFunction
log1p(x)

Accurate natural logarithm of1+x. ThrowsDomainError forReal arguments less than -1.

Examples

julia> log1p(-0.5)-0.6931471805599453julia> log1p(0)0.0julia> log1p(-2)ERROR: DomainError with -2.0:log1p was called with a real argument < -1 but will only return a complex result if called with a complex argument. Try log1p(Complex(x)).Stacktrace: [1] throw_complex_domainerror(::Symbol, ::Float64) at ./math.jl:31[...]
source
Base.Math.frexpFunction
frexp(val)

Return(x,exp) such thatx has a magnitude in the interval$[1/2, 1)$ or 0, andval is equal to$x \times 2^{exp}$.

See alsosignificand,exponent,ldexp.

Examples

julia> frexp(6.0)(0.75, 3)julia> significand(6.0), exponent(6.0)  # interval [1, 2) instead(1.5, 2)julia> frexp(0.0), frexp(NaN), frexp(-Inf)  # exponent would give an error((0.0, 0), (NaN, 0), (-Inf, 0))
source
Base.expMethod
exp(x)

Compute the natural base exponential ofx, in other words$ℯ^x$.

See alsoexp2,exp10 andcis.

Examples

julia> exp(1.0)2.718281828459045julia> exp(im * pi) ≈ cis(pi)true
source
Base.exp2Function
exp2(x)

Compute the base 2 exponential ofx, in other words$2^x$.

See alsoldexp,<<.

Examples

julia> exp2(5)32.0julia> 2^532julia> exp2(63) > typemax(Int)true
source
Base.exp10Function
exp10(x)

Compute the base 10 exponential ofx, in other words$10^x$.

Examples

julia> exp10(2)100.0julia> 10^2100
source
Base.Math.ldexpFunction
ldexp(x, n)

Compute$x \times 2^n$.

See alsofrexp,exponent.

Examples

julia> ldexp(5.0, 2)20.0
source
Base.Math.modfFunction
modf(x)

Return a tuple(fpart, ipart) of the fractional and integral parts of a number. Both parts have the same sign as the argument.

Examples

julia> modf(3.5)(0.5, 3.0)julia> modf(-3.5)(-0.5, -3.0)
source
Base.expm1Function
expm1(x)

Accurately compute$e^x-1$. It avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small values of x.

Examples

julia> expm1(1e-16)1.0e-16julia> exp(1e-16) - 10.0
source
Base.roundFunction
round([T,] x, [r::RoundingMode])round(x, [r::RoundingMode]; digits::Integer=0, base = 10)round(x, [r::RoundingMode]; sigdigits::Integer, base = 10)

Rounds the numberx.

Without keyword arguments,x is rounded to an integer value, returning a value of typeT, or of the same type ofx if noT is provided. AnInexactError will be thrown if the value is not representable byT, similar toconvert.

If thedigits keyword argument is provided, it rounds to the specified number of digits after the decimal place (or before if negative), in basebase.

If thesigdigits keyword argument is provided, it rounds to the specified number of significant digits, in basebase.

TheRoundingModer controls the direction of the rounding; the default isRoundNearest, which rounds to the nearest integer, with ties (fractional values of 0.5) being rounded to the nearest even integer. Note thatround may give incorrect results if the global rounding mode is changed (seerounding).

When rounding to a floating point type, will round to integers representable by that type (and Inf) rather than true integers. Inf is treated as one ulp greater than thefloatmax(T) for purposes of determining "nearest", similar toconvert.

Examples

julia> round(1.7)2.0julia> round(Int, 1.7)2julia> round(1.5)2.0julia> round(2.5)2.0julia> round(pi; digits=2)3.14julia> round(pi; digits=3, base=2)3.125julia> round(123.456; sigdigits=2)120.0julia> round(357.913; sigdigits=4, base=2)352.0julia> round(Float16, typemax(UInt128))Inf16julia> floor(Float16, typemax(UInt128))Float16(6.55e4)
Note

Rounding to specified digits in bases other than 2 can be inexact when operating on binary floating point numbers. For example, theFloat64 value represented by1.15 is actuallyless than 1.15, yet will be rounded to 1.2. For example:

julia> x = 1.151.15julia> big(1.15)1.149999999999999911182158029987476766109466552734375julia> x < 115//100truejulia> round(x, digits=1)1.2

Extensions

To extendround to new numeric types, it is typically sufficient to defineBase.round(x::NewType, r::RoundingMode).

source
Base.Rounding.RoundingModeType
RoundingMode

A type used for controlling the rounding mode of floating point operations (viarounding/setrounding functions), or as optional arguments for rounding to the nearest integer (via theround function).

Currently supported rounding modes are:

Julia 1.9

RoundFromZero requires at least Julia 1.9. Prior versions supportRoundFromZero forBigFloats only.

source
Base.Rounding.RoundNearestConstant
RoundNearest

The default rounding mode. Rounds to the nearest integer, with ties (fractional values of 0.5) being rounded to the nearest even integer.

source
Base.Rounding.RoundNearestTiesAwayConstant
RoundNearestTiesAway

Rounds to nearest integer, with ties rounded away from zero (C/C++round behaviour).

source
Base.Rounding.RoundNearestTiesUpConstant
RoundNearestTiesUp

Rounds to nearest integer, with ties rounded toward positive infinity (Java/JavaScriptround behaviour).

source
Base.Rounding.RoundToZeroConstant
RoundToZero

round using this rounding mode is an alias fortrunc.

source
Base.Rounding.RoundFromZeroConstant
RoundFromZero

Rounds away from zero.

Julia 1.9

RoundFromZero requires at least Julia 1.9. Prior versions supportRoundFromZero forBigFloats only.

Examples

julia> BigFloat("1.0000000000000001", 5, RoundFromZero)1.06
source
Base.Rounding.RoundUpConstant
RoundUp

round using this rounding mode is an alias forceil.

source
Base.Rounding.RoundDownConstant
RoundDown

round using this rounding mode is an alias forfloor.

source
Base.roundMethod
round(z::Complex[, RoundingModeReal, [RoundingModeImaginary]])round(z::Complex[, RoundingModeReal, [RoundingModeImaginary]]; digits=0, base=10)round(z::Complex[, RoundingModeReal, [RoundingModeImaginary]]; sigdigits, base=10)

Return the nearest integral value of the same type as the complex-valuedz toz, breaking ties using the specifiedRoundingModes. The firstRoundingMode is used for rounding the real components while the second is used for rounding the imaginary components.

RoundingModeReal andRoundingModeImaginary default toRoundNearest, which rounds to the nearest integer, with ties (fractional values of 0.5) being rounded to the nearest even integer.

Examples

julia> round(3.14 + 4.5im)3.0 + 4.0imjulia> round(3.14 + 4.5im, RoundUp, RoundNearestTiesUp)4.0 + 5.0imjulia> round(3.14159 + 4.512im; digits = 1)3.1 + 4.5imjulia> round(3.14159 + 4.512im; sigdigits = 3)3.14 + 4.51im
source
Base.ceilFunction
ceil([T,] x)ceil(x; digits::Integer= [, base = 10])ceil(x; sigdigits::Integer= [, base = 10])

ceil(x) returns the nearest integral value of the same type asx that is greater than or equal tox.

ceil(T, x) converts the result to typeT, throwing anInexactError if the ceiled value is not representable as aT.

Keywordsdigits,sigdigits andbase work as forround.

To supportceil for a new type, defineBase.round(x::NewType, ::RoundingMode{:Up}).

source
Base.floorFunction
floor([T,] x)floor(x; digits::Integer= [, base = 10])floor(x; sigdigits::Integer= [, base = 10])

floor(x) returns the nearest integral value of the same type asx that is less than or equal tox.

floor(T, x) converts the result to typeT, throwing anInexactError if the floored value is not representable aT.

Keywordsdigits,sigdigits andbase work as forround.

To supportfloor for a new type, defineBase.round(x::NewType, ::RoundingMode{:Down}).

source
Base.truncFunction
trunc([T,] x)trunc(x; digits::Integer= [, base = 10])trunc(x; sigdigits::Integer= [, base = 10])

trunc(x) returns the nearest integral value of the same type asx whose absolute value is less than or equal to the absolute value ofx.

trunc(T, x) converts the result to typeT, throwing anInexactError if the truncated value is not representable aT.

Keywordsdigits,sigdigits andbase work as forround.

To supporttrunc for a new type, defineBase.round(x::NewType, ::RoundingMode{:ToZero}).

See also:%,floor,unsigned,unsafe_trunc.

Examples

julia> trunc(2.22)2.0julia> trunc(-2.22, digits=1)-2.2julia> trunc(Int, -2.22)-2
source
Base.unsafe_truncFunction
unsafe_trunc(T, x)

Return the nearest integral value of typeT whose absolute value is less than or equal to the absolute value ofx. If the value is not representable byT, an arbitrary value will be returned. See alsotrunc.

Examples

julia> unsafe_trunc(Int, -2.2)-2julia> unsafe_trunc(Int, NaN)-9223372036854775808
source
Base.minFunction
min(x, y, ...)

Return the minimum of the arguments, with respect toisless. If any of the arguments ismissing, returnmissing. See also theminimum function to take the minimum element from a collection.

Examples

julia> min(2, 5, 1)1julia> min(4, missing, 6)missing
source
Base.maxFunction
max(x, y, ...)

Return the maximum of the arguments, with respect toisless. If any of the arguments ismissing, returnmissing. See also themaximum function to take the maximum element from a collection.

Examples

julia> max(2, 5, 1)5julia> max(5, missing, 6)missing
source
Base.minmaxFunction
minmax(x, y)

Return(min(x,y), max(x,y)).

See alsoextrema that returns(minimum(x), maximum(x)).

Examples

julia> minmax('c','b')('b', 'c')
source
Base.clampFunction
clamp(x, lo, hi)

Returnx iflo <= x <= hi. Ifx > hi, returnhi. Ifx < lo, returnlo. Arguments are promoted to a common type.

See alsoclamp!,min,max.

Julia 1.3

missing as the first argument requires at least Julia 1.3.

Examples

julia> clamp.([pi, 1.0, big(10)], 2.0, 9.0)3-element Vector{BigFloat}: 3.141592653589793238462643383279502884197169399375105820974944592307816406286198 2.0 9.0julia> clamp.([11, 8, 5], 10, 6)  # an example where lo > hi3-element Vector{Int64}:  6  6 10
source
clamp(x, T)::T

Clampx betweentypemin(T) andtypemax(T) and convert the result to typeT.

See alsotrunc.

Examples

julia> clamp(200, Int8)127julia> clamp(-200, Int8)-128julia> trunc(Int, 4pi^2)39
source
clamp(x::Integer, r::AbstractUnitRange)

Clampx to lie within ranger.

Julia 1.6

This method requires at least Julia 1.6.

source
Base.clamp!Function
clamp!(array::AbstractArray, lo, hi)

Restrict values inarray to the specified range, in-place. See alsoclamp.

Julia 1.3

missing entries inarray require at least Julia 1.3.

Examples

julia> row = collect(-4:4)';julia> clamp!(row, 0, Inf)1×9 adjoint(::Vector{Int64}) with eltype Int64: 0  0  0  0  0  1  2  3  4julia> clamp.((-4:4)', 0, Inf)1×9 Matrix{Float64}: 0.0  0.0  0.0  0.0  0.0  1.0  2.0  3.0  4.0
source
Base.absFunction
abs(x)

The absolute value ofx.

Whenabs is applied to signed integers, overflow may occur, resulting in the return of a negative value. This overflow occurs only whenabs is applied to the minimum representable value of a signed integer. That is, whenx == typemin(typeof(x)),abs(x) == x < 0, not-x as might be expected.

See also:abs2,unsigned,sign.

Examples

julia> abs(-3)3julia> abs(1 + im)1.4142135623730951julia> abs.(Int8[-128 -127 -126 0 126 127])  # overflow at typemin(Int8)1×6 Matrix{Int8}: -128  127  126  0  126  127julia> maximum(abs, [1, -2, 3, -4])4
source
Base.CheckedModule
Checked

The Checked module provides arithmetic functions for the built-in signed and unsigned Integer types which throw an error when an overflow occurs. They are named likechecked_sub,checked_div, etc. In addition,add_with_overflow,sub_with_overflow,mul_with_overflow return both the unchecked results and a boolean value denoting the presence of an overflow.

source
Base.Checked.checked_absFunction
Base.checked_abs(x)

Calculatesabs(x), checking for overflow errors where applicable. For example, standard two's complement signed integers (e.g.Int) cannot representabs(typemin(Int)), thus leading to an overflow.

The overflow protection may impose a perceptible performance penalty.

source
Base.Checked.checked_negFunction
Base.checked_neg(x)

Calculates-x, checking for overflow errors where applicable. For example, standard two's complement signed integers (e.g.Int) cannot represent-typemin(Int), thus leading to an overflow.

The overflow protection may impose a perceptible performance penalty.

source
Base.Checked.checked_addFunction
Base.checked_add(x, y)

Calculatesx+y, checking for overflow errors where applicable.

The overflow protection may impose a perceptible performance penalty.

source
Base.Checked.checked_subFunction
Base.checked_sub(x, y)

Calculatesx-y, checking for overflow errors where applicable.

The overflow protection may impose a perceptible performance penalty.

source
Base.Checked.checked_mulFunction
Base.checked_mul(x, y)

Calculatesx*y, checking for overflow errors where applicable.

The overflow protection may impose a perceptible performance penalty.

source
Base.Checked.checked_divFunction
Base.checked_div(x, y)

Calculatesdiv(x,y), checking for overflow errors where applicable.

The overflow protection may impose a perceptible performance penalty.

source
Base.Checked.checked_remFunction
Base.checked_rem(x, y)

Calculatesx%y, checking for overflow errors where applicable.

The overflow protection may impose a perceptible performance penalty.

source
Base.Checked.checked_fldFunction
Base.checked_fld(x, y)

Calculatesfld(x,y), checking for overflow errors where applicable.

The overflow protection may impose a perceptible performance penalty.

source
Base.Checked.checked_modFunction
Base.checked_mod(x, y)

Calculatesmod(x,y), checking for overflow errors where applicable.

The overflow protection may impose a perceptible performance penalty.

source
Base.Checked.checked_cldFunction
Base.checked_cld(x, y)

Calculatescld(x,y), checking for overflow errors where applicable.

The overflow protection may impose a perceptible performance penalty.

source
Base.Checked.checked_powFunction
Base.checked_pow(x, y)

Calculates^(x,y), checking for overflow errors where applicable.

The overflow protection may impose a perceptible performance penalty.

source
Base.Checked.add_with_overflowFunction
Base.add_with_overflow(x, y) -> (r, f)

Calculatesr = x+y, with the flagf indicating whether overflow has occurred.

source
Base.Checked.sub_with_overflowFunction
Base.sub_with_overflow(x, y) -> (r, f)

Calculatesr = x-y, with the flagf indicating whether overflow has occurred.

source
Base.Checked.mul_with_overflowFunction
Base.mul_with_overflow(x, y) -> (r, f)

Calculatesr = x*y, with the flagf indicating whether overflow has occurred.

source
Base.abs2Function
abs2(x)

Squared absolute value ofx.

This can be faster thanabs(x)^2, especially for complex numbers whereabs(x) requires a square root viahypot.

See alsoabs,conj,real.

Examples

julia> abs2(-3)9julia> abs2(3.0 + 4.0im)25.0julia> sum(abs2, [1+2im, 3+4im])  # LinearAlgebra.norm(x)^230
source
Base.copysignFunction
copysign(x, y) -> z

Returnz which has the magnitude ofx and the same sign asy.

Examples

julia> copysign(1, -2)-1julia> copysign(-1, 2)1
source
Base.signFunction
sign(x)

Return zero ifx==0 and$x/|x|$ otherwise (i.e., ±1 for realx).

See alsosignbit,zero,copysign,flipsign.

Examples

julia> sign(-4.0)-1.0julia> sign(99)1julia> sign(-0.0)-0.0julia> sign(0 + im)0.0 + 1.0im
source
Base.signbitFunction
signbit(x)

Returntrue if the value of the sign ofx is negative, otherwisefalse.

See alsosign andcopysign.

Examples

julia> signbit(-4)truejulia> signbit(5)falsejulia> signbit(5.5)falsejulia> signbit(-4.1)true
source
Base.flipsignFunction
flipsign(x, y)

Returnx with its sign flipped ify is negative. For exampleabs(x) = flipsign(x,x).

Examples

julia> flipsign(5, 3)5julia> flipsign(5, -3)-5
source
Base.sqrtMethod
sqrt(x)

Return$\sqrt{x}$.

ThrowsDomainError for negativeReal arguments. Use complex negative arguments instead. Note thatsqrt has a branch cut along the negative real axis.

The prefix operator is equivalent tosqrt.

See also:hypot.

Examples

julia> sqrt(big(81))9.0julia> sqrt(big(-81))ERROR: DomainError with -81.0:NaN result for non-NaN input.Stacktrace: [1] sqrt(::BigFloat) at ./mpfr.jl:501[...]julia> sqrt(big(complex(-81)))0.0 + 9.0imjulia> sqrt(-81 - 0.0im)  # -0.0im is below the branch cut0.0 - 9.0imjulia> .√(1:4)4-element Vector{Float64}: 1.0 1.4142135623730951 1.7320508075688772 2.0
source
Base.isqrtFunction
isqrt(n::Integer)

Integer square root: the largest integerm such thatm*m <= n.

julia> isqrt(5)2
source
Base.Math.cbrtMethod
cbrt(x::Real)

Return the cube root ofx, i.e.$x^{1/3}$. Negative values are accepted (returning the negative real root when$x < 0$).

The prefix operator is equivalent tocbrt.

Examples

julia> cbrt(big(27))3.0julia> cbrt(big(-27))-3.0
source
Base.realFunction
real(z)

Return the real part of the complex numberz.

See also:imag,reim,complex,isreal,Real.

Examples

julia> real(1 + 3im)1
source
real(T::Type)

Return the type that represents the real part of a value of typeT. e.g: forT == Complex{R}, returnsR. Equivalent totypeof(real(zero(T))).

Examples

julia> real(Complex{Int})Int64julia> real(Float64)Float64
source
real(A::AbstractArray)

Return an array containing the real part of each entry in arrayA.

Equivalent toreal.(A), except that wheneltype(A) <: RealA is returned without copying, and that whenA has zero dimensions, a 0-dimensional array is returned (rather than a scalar).

Examples

julia> real([1, 2im, 3 + 4im])3-element Vector{Int64}: 1 0 3julia> real(fill(2 - im))0-dimensional Array{Int64, 0}:2
source
Base.imagFunction
imag(z)

Return the imaginary part of the complex numberz.

See also:conj,reim,adjoint,angle.

Examples

julia> imag(1 + 3im)3
source
imag(A::AbstractArray)

Return an array containing the imaginary part of each entry in arrayA.

Equivalent toimag.(A), except that whenA has zero dimensions, a 0-dimensional array is returned (rather than a scalar).

Examples

julia> imag([1, 2im, 3 + 4im])3-element Vector{Int64}: 0 2 4julia> imag(fill(2 - im))0-dimensional Array{Int64, 0}:-1
source
Base.reimFunction
reim(z)

Return a tuple of the real and imaginary parts of the complex numberz.

Examples

julia> reim(1 + 3im)(1, 3)
source
reim(A::AbstractArray)

Return a tuple of two arrays containing respectively the real and the imaginary part of each entry inA.

Equivalent to(real.(A), imag.(A)), except that wheneltype(A) <: RealA is returned without copying to represent the real part, and that whenA has zero dimensions, a 0-dimensional array is returned (rather than a scalar).

Examples

julia> reim([1, 2im, 3 + 4im])([1, 0, 3], [0, 2, 4])julia> reim(fill(2 - im))(fill(2), fill(-1))
source
Base.conjFunction
conj(z)

Compute the complex conjugate of a complex numberz.

See also:angle,adjoint.

Examples

julia> conj(1 + 3im)1 - 3im
source
conj(A::AbstractArray)

Return an array containing the complex conjugate of each entry in arrayA.

Equivalent toconj.(A), except that wheneltype(A) <: RealA is returned without copying, and that whenA has zero dimensions, a 0-dimensional array is returned (rather than a scalar).

Examples

julia> conj([1, 2im, 3 + 4im])3-element Vector{Complex{Int64}}: 1 + 0im 0 - 2im 3 - 4imjulia> conj(fill(2 - im))0-dimensional Array{Complex{Int64}, 0}:2 + 1im
source
Base.angleFunction
angle(z)

Compute the phase angle in radians of a complex numberz.

Returns a number-pi ≤ angle(z) ≤ pi, and is thus discontinuous along the negative real axis.

See also:atan,cis,rad2deg.

Examples

julia> rad2deg(angle(1 + im))45.0julia> rad2deg(angle(1 - im))-45.0julia> rad2deg(angle(-1 + 1e-20im))180.0julia> rad2deg(angle(-1 - 1e-20im))-180.0
source
Base.cisFunction
cis(x)

More efficient method forexp(im*x) by using Euler's formula:$\cos(x) + i \sin(x) = \exp(i x)$.

See alsocispi,sincos,exp,angle.

Examples

julia> cis(π) ≈ -1true
source
Base.cispiFunction
cispi(x)

More accurate method forcis(pi*x) (especially for largex).

See alsocis,sincospi,exp,angle.

Examples

julia> cispi(10000)1.0 + 0.0imjulia> cispi(0.25 + 1im)0.030556854645954562 + 0.03055685464595456im
Julia 1.6

This function requires Julia 1.6 or later.

source
Base.binomialFunction
binomial(n::Integer, k::Integer)

Thebinomial coefficient$\binom{n}{k}$, being the coefficient of the$k$th term in the polynomial expansion of$(1+x)^n$.

If$n$ is non-negative, then it is the number of ways to choosek out ofn items:

\[\binom{n}{k} = \frac{n!}{k! (n-k)!}\]

where$n!$ is thefactorial function.

If$n$ is negative, then it is defined in terms of the identity

\[\binom{n}{k} = (-1)^k \binom{k-n-1}{k}\]

See alsofactorial.

Examples

julia> binomial(5, 3)10julia> factorial(5) ÷ (factorial(5-3) * factorial(3))10julia> binomial(-5, 3)-35

External links

source
binomial(x::Number, k::Integer)

The generalized binomial coefficient, defined fork ≥ 0 by the polynomial

\[\frac{1}{k!} \prod_{j=0}^{k-1} (x - j)\]

Whenk < 0 it returns zero.

For the case of integerx, this is equivalent to the ordinary integer binomial coefficient

\[\binom{n}{k} = \frac{n!}{k! (n-k)!}\]

Further generalizations to non-integerk are mathematically possible, but involve the Gamma function and/or the beta function, which are not provided by the Julia standard library but are available in external packages such asSpecialFunctions.jl.

External links

source
Base.factorialFunction
factorial(n::Integer)

Factorial ofn. Ifn is anInteger, the factorial is computed as an integer (promoted to at least 64 bits). Note that this may overflow ifn is not small, but you can usefactorial(big(n)) to compute the result exactly in arbitrary precision.

See alsobinomial.

Examples

julia> factorial(6)720julia> factorial(21)ERROR: OverflowError: 21 is too large to look up in the table; consider using `factorial(big(21))` insteadStacktrace:[...]julia> factorial(big(21))51090942171709440000

External links

source
Base.gcdFunction
gcd(x, y...)

Greatest common (positive) divisor (or zero if all arguments are zero). The arguments may be integer and rational numbers.

Julia 1.4

Rational arguments require Julia 1.4 or later.

Examples

julia> gcd(6, 9)3julia> gcd(6, -9)3julia> gcd(6, 0)6julia> gcd(0, 0)0julia> gcd(1//3, 2//3)1//3julia> gcd(1//3, -2//3)1//3julia> gcd(1//3, 2)1//3julia> gcd(0, 0, 10, 15)5
source
Base.lcmFunction
lcm(x, y...)

Least common (positive) multiple (or zero if any argument is zero). The arguments may be integer and rational numbers.

Julia 1.4

Rational arguments require Julia 1.4 or later.

Examples

julia> lcm(2, 3)6julia> lcm(-2, 3)6julia> lcm(0, 3)0julia> lcm(0, 0)0julia> lcm(1//3, 2//3)2//3julia> lcm(1//3, -2//3)2//3julia> lcm(1//3, 2)2//1julia> lcm(1, 3, 5, 7)105
source
Base.gcdxFunction
gcdx(a, b)

Computes the greatest common (positive) divisor ofa andb and their Bézout coefficients, i.e. the integer coefficientsu andv that satisfy$ua+vb = d = gcd(a, b)$.$gcdx(a, b)$ returns$(d, u, v)$.

The arguments may be integer and rational numbers.

Julia 1.4

Rational arguments require Julia 1.4 or later.

Examples

julia> gcdx(12, 42)(6, -3, 1)julia> gcdx(240, 46)(2, -9, 47)
Note

Bézout coefficients arenot uniquely defined.gcdx returns the minimal Bézout coefficients that are computed by the extended Euclidean algorithm. (Ref: D. Knuth, TAoCP, 2/e, p. 325, Algorithm X.) For signed integers, these coefficientsu andv are minimal in the sense that$|u| < |b/d|$ and$|v| < |a/d|$. Furthermore, the signs ofu andv are chosen so thatd is positive. For unsigned integers, the coefficientsu andv might be near theirtypemax, and the identity then holds only via the unsigned integers' modulo arithmetic.

source
Base.ispow2Function
ispow2(n::Number) -> Bool

Test whethern is an integer power of two.

See alsocount_ones,prevpow,nextpow.

Examples

julia> ispow2(4)truejulia> ispow2(5)falsejulia> ispow2(4.5)falsejulia> ispow2(0.25)truejulia> ispow2(1//8)true
Julia 1.6

Support for non-Integer arguments was added in Julia 1.6.

source
Base.nextpowFunction
nextpow(a, x)

The smallesta^n not less thanx, wheren is a non-negative integer.a must be greater than 1, andx must be greater than 0.

See alsoprevpow.

Examples

julia> nextpow(2, 7)8julia> nextpow(2, 9)16julia> nextpow(5, 20)25julia> nextpow(4, 16)16
source
Base.prevpowFunction
prevpow(a, x)

The largesta^n not greater thanx, wheren is a non-negative integer.a must be greater than 1, andx must not be less than 1.

See alsonextpow,isqrt.

Examples

julia> prevpow(2, 7)4julia> prevpow(2, 9)8julia> prevpow(5, 20)5julia> prevpow(4, 16)16
source
Base.nextprodFunction
nextprod(factors::Union{Tuple,AbstractVector}, n)

Next integer greater than or equal ton that can be written as$\prod k_i^{p_i}$ for integers$p_1$,$p_2$, etcetera, for factors$k_i$ infactors.

Examples

julia> nextprod((2, 3), 105)108julia> 2^2 * 3^3108
Julia 1.6

The method that accepts a tuple requires Julia 1.6 or later.

source
Base.invmodFunction
invmod(n::Integer, m::Integer)

Take the inverse ofn modulom:y such that$n y = 1 \pmod m$, and$div(y,m) = 0$. This will throw an error if$m = 0$, or if$gcd(n,m) \neq 1$.

Examples

julia> invmod(2, 5)3julia> invmod(2, 3)2julia> invmod(5, 6)5
source
invmod(n::Integer, T) where {T <: Base.BitInteger}invmod(n::T) where {T <: Base.BitInteger}

Compute the modular inverse ofn in the integer ring of typeT, i.e. modulo2^N whereN = 8*sizeof(T) (e.g.N = 32 forInt32). In other words these methods satisfy the following identities:

n * invmod(n) == 1(n * invmod(n, T)) % T == 1(n % T) * invmod(n, T) == 1

Note that* here is modular multiplication in the integer ring,T.

Specifying the modulus implied by an integer type as an explicit value is often inconvenient since the modulus is by definition too big to be represented by the type.

The modular inverse is computed much more efficiently than the general case using the algorithm described in https://arxiv.org/pdf/2204.04342.pdf.

Julia 1.11

Theinvmod(n) andinvmod(n, T) methods require Julia 1.11 or later.

source
Base.powermodFunction
powermod(x::Integer, p::Integer, m)

Compute$x^p \pmod m$.

Examples

julia> powermod(2, 6, 5)4julia> mod(2^6, 5)4julia> powermod(5, 2, 20)5julia> powermod(5, 2, 19)6julia> powermod(5, 3, 19)11
source
Base.ndigitsFunction
ndigits(n::Integer; base::Integer=10, pad::Integer=1)

Compute the number of digits in integern written in basebase (base must not be in[-1, 0, 1]), optionally padded with zeros to a specified size (the result will never be less thanpad).

See alsodigits,count_ones.

Examples

julia> ndigits(0)1julia> ndigits(12345)5julia> ndigits(1022, base=16)3julia> string(1022, base=16)"3fe"julia> ndigits(123, pad=5)5julia> ndigits(-123)3
source
Base.add_sumFunction
Base.add_sum(x, y)

The reduction operator used insum. The main difference from+ is that small integers are promoted toInt/UInt.

source
Base.widemulFunction
widemul(x, y)

Multiplyx andy, giving the result as a larger type.

See alsopromote,Base.add_sum.

Examples

julia> widemul(Float32(3.0), 4.0) isa BigFloattruejulia> typemax(Int8) * typemax(Int8)1julia> widemul(typemax(Int8), typemax(Int8))  # == 127^216129
source
Base.Math.evalpolyFunction
evalpoly(x, p)

Evaluate the polynomial$\sum_k x^{k-1} p[k]$ for the coefficientsp[1],p[2], ...; that is, the coefficients are given in ascending order by power ofx. Loops are unrolled at compile time if the number of coefficients is statically known, i.e. whenp is aTuple. This function generates efficient code using Horner's method ifx is real, or using a Goertzel-like[DK62] algorithm ifx is complex.

Julia 1.4

This function requires Julia 1.4 or later.

Examples

julia> evalpoly(2, (1, 2, 3))17
source
Base.Math.@evalpolyMacro
@evalpoly(z, c...)

Evaluate the polynomial$\sum_k z^{k-1} c[k]$ for the coefficientsc[1],c[2], ...; that is, the coefficients are given in ascending order by power ofz. This macro expands to efficient inline code that uses either Horner's method or, for complexz, a more efficient Goertzel-like algorithm.

See alsoevalpoly.

Examples

julia> @evalpoly(3, 1, 0, 1)10julia> @evalpoly(2, 1, 0, 1)5julia> @evalpoly(2, 1, 1, 1)7
source
Base.FastMath.@fastmathMacro
@fastmath expr

Execute a transformed version of the expression, which calls functions that may violate strict IEEE semantics. This allows the fastest possible operation, but results are undefined – be careful when doing this, as it may change numerical results.

This sets theLLVM Fast-Math flags, and corresponds to the-ffast-math option in clang. Seethe notes on performance annotations for more details.

Examples

julia> @fastmath 1+23julia> @fastmath(sin(3))0.1411200080598672
source

Customizable binary operators

Some unicode characters can be used to define new binary operators that support infix notation. For example⊗(x,y) = kron(x,y) defines the (otimes) function to be the Kronecker product, and one can call it as binary operator using infix syntax:C = A ⊗ B as well as with the usual prefix syntaxC = ⊗(A,B).

Other characters that support such extensions include \odot and \oplus

The complete list is in the parser code:https://github.com/JuliaLang/julia/blob/master/src/julia-parser.scm

Those that are parsed like* (in terms of precedence) include* / ÷ % & ⋅ ∘ × |\\| ∩ ∧ ⊗ ⊘ ⊙ ⊚ ⊛ ⊠ ⊡ ⊓ ∗ ∙ ∤ ⅋ ≀ ⊼ ⋄ ⋆ ⋇ ⋉ ⋊ ⋋ ⋌ ⋏ ⋒ ⟑ ⦸ ⦼ ⦾ ⦿ ⧶ ⧷ ⨇ ⨰ ⨱ ⨲ ⨳ ⨴ ⨵ ⨶ ⨷ ⨸ ⨻ ⨼ ⨽ ⩀ ⩃ ⩄ ⩋ ⩍ ⩎ ⩑ ⩓ ⩕ ⩘ ⩚ ⩜ ⩞ ⩟ ⩠ ⫛ ⊍ ▷ ⨝ ⟕ ⟖ ⟗ and those that are parsed like+ include+ - |\|| ⊕ ⊖ ⊞ ⊟ |++| ∪ ∨ ⊔ ± ∓ ∔ ∸ ≏ ⊎ ⊻ ⊽ ⋎ ⋓ ⟇ ⧺ ⧻ ⨈ ⨢ ⨣ ⨤ ⨥ ⨦ ⨧ ⨨ ⨩ ⨪ ⨫ ⨬ ⨭ ⨮ ⨹ ⨺ ⩁ ⩂ ⩅ ⩊ ⩌ ⩏ ⩐ ⩒ ⩔ ⩖ ⩗ ⩛ ⩝ ⩡ ⩢ ⩣ There are many others that are related to arrows, comparisons, and powers.

  • DK62Donald Knuth, Art of Computer Programming, Volume 2: Seminumerical Algorithms, Sec. 4.6.4.

Settings


This document was generated withDocumenter.jl version 1.8.0 onWednesday 9 July 2025. Using Julia version 1.11.6.


[8]ページ先頭

©2009-2025 Movatter.jp