Mathematics

Mathematical Operators

Base.:- — Method
-(x)

Unary minus operator.

See also abs, flipsign.

Examples

julia> -1
-1

julia> -(2)
-2

julia> -[1 2; 3 4]
2×2 Matrix{Int64}:
 -1  -2
 -3  -4

julia> -(true)  # promotes to Int
-1

julia> -(0x003)
0xfffd
source
Base.:+ — Function
+(x, y...)

Addition operator.

Infix x+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 default Int, when adding large numbers.

Examples

julia> 1 + 20 + 4
25

julia> +(1, 20, 4)
25

julia> [1,2] + [3,4]
2-element Vector{Int64}:
 4
 6

julia> typemax(Int) + 1 < 0
true
source
dt::Date + t::Time -> DateTime

The addition of a Date with a Time produces a DateTime. The hour, minute, second, and millisecond parts of the Time are used along with the year, month, and day of the Date to create the new DateTime. Non-zero microseconds or nanoseconds in the Time type will result in an InexactError being thrown.

source
Base.:- — Method
-(x, y)

Subtraction operator.

Examples

julia> 2 - 3
-1

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

Multiplication operator.

Infix x*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 as 2pi 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 with x) is forbidden as it clashes with unsigned integer literals: 0x01 isa UInt8.

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

Examples

julia> 2 * 7 * 8
112

julia> *(2, 7, 8)
112

julia> [2 0; 0 3] * [1, 10]  # matrix * vector
2-element Vector{Int64}:
  2
 30

julia> 1/2pi, 1/2*pi  # juxtaposition has higher precedence
(0.15915494309189535, 1.5707963267948966)

julia> x = [1, 2]; x'x  # adjoint vector * vector
5
source
Base.:/ — Function
/(x, y)

Right division operator: multiplication of x by the inverse of y on the right.

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

Examples

julia> 1/2
0.5

julia> 4/2
2.0

julia> 4.5/2
2.25
source
A / B

Matrix right-division: A / B is equivalent to (B' \ A')' where \ is the left-division operator. For square matrices, the result X is such that A == 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 / B
2×3 Matrix{Float64}:
 -0.65   3.75  -1.2
  3.25  -2.75   1.0

julia> isapprox(A, X*B)
true

julia> isapprox(X, A*pinv(B))
true
source
Base.:\ — Method
\(x, y)

Left division operator: multiplication of y by the inverse of x on the left. Gives floating-point results for integer arguments.

Examples

julia> 3 \ 6
2.0

julia> inv(3) * 6
2.0

julia> A = [4 3; 2 1]; x = [5, 6];

julia> A \ x
2-element Vector{Float64}:
  6.5
 -7.0

julia> inv(A) * x
2-element Vector{Float64}:
  6.5
 -7.0
source
Base.:^ — Method
^(x, y)

Exponentiation operator.

If x and y are integers, the result may overflow. To enter numbers in scientific notation, use Float64 literals such as 1.2e3 rather than 1.2 * 10^3.

If y is an Int literal (e.g. 2 in x^2 or -3 in x^-3), the Julia code x^y is transformed by the compiler to Base.literal_pow(^, x, Val(y)), to enable compile-time specialization on the value of the exponent. (As a default fallback we have Base.literal_pow(^, x, Val(y)) = ^(x,y), where usually ^ == Base.^ unless ^ has been defined in the calling namespace.) If y is a negative integer literal, then Base.literal_pow transforms the operation to inv(x)^-y by default, where -y is positive.

See also exp2, <<.

Examples

julia> 3^5
243

julia> 3^-1  # uses Base.literal_pow
0.3333333333333333

julia> p = -1;

julia> 3^p
ERROR: DomainError with -1:
Cannot raise an integer x to a negative power -1.
[...]

julia> 3.0^p
0.3333333333333333

julia> 10^19 > 0  # integer overflow
false

julia> big(10)^19 == 1e19
true
source
Base.fma — Function
fma(x, y, z)

Compute x*y+z without rounding the intermediate result x*y. On some systems this is significantly more expensive than x*y+z. fma is used to improve accuracy in certain algorithms. See muladd.

source
Base.muladd — Function
muladd(x, y, z)

Combined multiply-add: computes x*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 an fma 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. See fma.

Examples

julia> muladd(3, 2, 1)
7

julia> 3 * 2 + 1
7
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 as A*y, but z 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
source
Base.inv — Method
inv(x)

Return the multiplicative inverse of x, such that x*inv(x) or inv(x)*x yields one(x) (the multiplicative identity) up to roundoff errors.

If x is a number, this is essentially the same as one(x)/x, but for some types inv(x) may be slightly more efficient.

Examples

julia> inv(2)
0.5

julia> inv(1 + 2im)
0.2 - 0.4im

julia> inv(1 + 2im) * (1 + 2im)
1.0 + 0.0im

julia> inv(2//3)
3//2
Julia 1.2

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

source
Base.div — Function
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 ÷ 4
2

julia> -5 ÷ 3
-1

julia> 5.0 ÷ 2
2.0

julia> 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.div — Method
div(x, y, r::RoundingMode=RoundToZero)

The quotient from Euclidean (integer) division. Computes x / y, rounded to an integer according to the rounding mode r. In other words, the quantity

round(x / y, r)

without any intermediate rounding.

Julia 1.4

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

See also fld and cld, 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)
1
julia> div(4, 3, RoundDown) # Matches fld(4, 3)
1
julia> div(4, 3, RoundUp) # Matches cld(4, 3)
2
julia> div(5, 2, RoundNearest)
2
julia> div(5, 2, RoundNearestTiesAway)
3
julia> div(-5, 2, RoundNearest)
-2
julia> div(-5, 2, RoundNearestTiesAway)
-3
julia> div(-5, 2, RoundNearestTiesUp)
-2
julia> div(4, 3, RoundFromZero)
2
julia> div(-4, 3, RoundFromZero)
-2
Floating-point numbers

Accurate results for floating-point arguments are only guaranteed when the mathematical value $\frac{x}{y}$ is within the range of exactly representable integers for the given floating-point type, that is, when eps(x/y) ≤ 1, or in other words, given a = div(x, y), when abs(a) < maxintfloat(a).

Because div(x, y) implements strict truncated rounding based on the quotient and remainder of the Euclidean division, and because the binary representation of floating-point numbers (in most cases) only approximates the decimal representation we use, unintuitive situations can arise. For example:

julia> div(6.0, 0.1)
59.0
julia> 6.0 / 0.1
60.0
julia> 6.0 / big(0.1)
59.99999999999999666933092612453056361837965690217069245739573412231113406246995

What is happening here is that the binary representation of the Float64 number written as 0.1 is slightly larger than the numerical value $0.1$ (just like 0.3333333333333333 is less than $1/3$ in decimal), while 6.0 represents the number $6$ precisely. Therefore the mathematical result of 6.0 divided by (the Float64 representation of) 0.1 is slightly less than $60$. The result of the floating-point division is rounded to precisely 60.0, but div(6.0, 0.1, RoundToZero) takes account of the quotient and (here non-zero) remainder of the Euclidean division, so the result is 59.0.

See also rem, divrem.

source
Base.fld — Function
fld(x, y)

Largest integer less than or equal to x / y. Equivalent to div(x, y, RoundDown).

See also div, cld, mod, fldmod.

Examples

julia> fld(7.3, 5.5)
1.0

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

Accurate results for floating-point arguments are only guaranteed when the mathematical value $\frac{x}{y}$ is within the range of exactly representable integers for the given floating-point type, that is, when eps(x/y) ≤ 1, or in other words, given a = fld(x, y), when abs(a) < maxintfloat(a).

Because fld(x, y) implements strict floored rounding based on the quotient and remainder of the Euclidean division, and because the binary representation of floating-point numbers (in most cases) only approximates the decimal representation we use, unintuitive situations can arise. For example:

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

What is happening here is that the binary representation of the Float64 number written as 0.1 is slightly larger than the numerical value $0.1$ (just like 0.3333333333333333 is less than $1/3$ in decimal), while 6.0 represents the number $6$ precisely. Therefore the mathematical result of 6.0 divided by (the Float64 representation of) 0.1 is slightly less than $60$. The result of the floating-point division is rounded to precisely 60.0, but fld(6.0, 0.1) takes account of the quotient and (here non-zero) remainder of the Euclidean division, so the result is 59.0.

See also rem, divrem.

source
Base.cld — Function
cld(x, y)

Smallest integer larger than or equal to x / y. Equivalent to div(x, y, RoundUp).

See also div, fld, mod1, cldmod1.

Examples

julia> cld(5.5, 2.2)
3.0

julia> cld.(-5:5, 3)'
1×11 adjoint(::Vector{Int64}) with eltype Int64:
 -1  -1  -1  0  0  0  1  1  1  2  2
Floating-point numbers

Accurate results for floating-point arguments are only guaranteed when the mathematical value $\frac{x}{y}$ is within the range of exactly representable integers for the given floating-point type, that is, when eps(x/y) ≤ 1, or in other words, given a = cld(x, y), when abs(a) < maxintfloat(a).

Because cld(x, y) implements strict ceiled rounding based on the quotient and remainder of the Euclidean division, and because the binary representation of floating-point numbers (in most cases) only approximates the decimal representation we use, unintuitive situations can arise. For example:

julia> cld(3.0, 0.3)
11.0
julia> 3.0 / 0.3
10.0
julia> 3.0 / big(0.3)
10.00000000000000037007434154171886050337904945061778828900298697586147515340753

What is happening here is that the binary representation of the Float64 number written as 0.3 is slightly less than the numerical value $0.3$ (just like 0.3333333333333333 is less than $1/3$ in decimal), while 3.0 represents the number $3$ precisely. Therefore the mathematical result of 3.0 divided by (the Float64 representation of) 0.3 is slightly larger than $10$. The result of the floating-point division is rounded to precisely 10.0, but cld(3.0, 0.3) takes account of the quotient and (here non-zero) remainder of the Euclidean division, so the result is 11.0.

See also rem, divrem.

source
Base.rem — Function
rem(x, y)
%(x, y)

Remainder from Euclidean division, returning a value of the same sign as x, and smaller in magnitude than y. This value is always exact.

See also div, mod, mod1, divrem.

Examples

julia> x = 15; y = 4;

julia> x % y
3

julia> x == div(x, y) * y + rem(x, y)
true

julia> 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.rem — Method
rem(x, y, r::RoundingMode=RoundToZero)

Compute the remainder of x after integer division by y, with the quotient rounded according to the rounding mode r. In other words, the quantity

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

without any intermediate rounding.

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

  • if r == RoundToZero (default), then the result is exact, and in the interval $[0, |y|)$ if x is positive, or $(-|y|, 0]$ otherwise. See also RoundToZero.

  • if r == RoundDown, then the result is in the interval $[0, |y|)$ if y is positive, or $(-|y|, 0]$ otherwise. The result may not be exact if x and y have different signs, and abs(x) < abs(y). See also RoundDown.

  • if r == RoundUp, then the result is in the interval $(-|y|, 0]$ if y is positive, or $[0, |y|)$ otherwise. The result may not be exact if x and y have the same sign, and abs(x) < abs(y). See also RoundUp.

  • if r == RoundFromZero, then the result is in the interval $(-|y|, 0]$ if x is positive, or $[0, |y|)$ otherwise. The result may not be exact if x and y have the same sign, and abs(x) < abs(y). See also RoundFromZero.

Julia 1.9

RoundFromZero requires at least Julia 1.9.

Examples:

julia> x = 9; y = 4;

julia> x % y  # same as rem(x, y)
1

julia> x ÷ y  # same as div(x, y)
2

julia> x == div(x, y) * y + rem(x, y)
true
source
Base.Math.rem2pi — Function
rem2pi(x, r::RoundingMode)

Compute the remainder of x after integer division by 2π, with the quotient rounded according to the rounding mode r. 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 than rem(x,2π,r)

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

  • if r == RoundToZero, then the result is in the interval $[0, 2π]$ if x is positive,. or $[-2π, 0]$ otherwise. See also RoundToZero.

  • if r == RoundDown, then the result is in the interval $[0, 2π]$. See also RoundDown.

  • if r == RoundUp, then the result is in the interval $[-2π, 0]$. See also RoundUp.

Examples

julia> rem2pi(7pi/4, RoundNearest)
-0.7853981633974485

julia> rem2pi(7pi/4, RoundDown)
5.497787143782138
source
Base.mod — Function
rem(x::Integer, T::Type{<:Integer})::T
mod(x::Integer, T::Type{<:Integer})::T
%(x::Integer, T::Type{<:Integer})::T

Find y::T such that x ≡ y (mod n), where n is the number of integers representable in T, and y is an integer in [typemin(T),typemax(T)]. If T can represent any integer (e.g. T == BigInt), then this operation corresponds to a conversion to T.

Examples

julia> x = 129 % Int8
-127

julia> typeof(x)
Int8

julia> x = 129 % BigInt
129

julia> typeof(x)
BigInt
source
mod(x, y)
rem(x, y, RoundDown)

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

The result will have the same sign as y if isfinite(y), and magnitude less than abs(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 to y, then it may be rounded to y.

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

julia> mod(8, 3)
2

julia> mod(9, 3)
0

julia> mod(8.9, 3)
2.9000000000000004

julia> mod(eps(), 3)
2.220446049250313e-16

julia> mod(-eps(), 3)
3.0

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

Find y in the range r such that x ≡ y (mod n), where n = length(r), i.e. y = mod(x - first(r), n) + first(r).

See also mod1.

Examples

julia> mod(0, Base.OneTo(3))  # mod1(0, 3)
3

julia> mod(3, 0:2)  # mod(3, 3)
0
Julia 1.3

This method requires at least Julia 1.3.

source
Base.Math.mod2pi — Function
mod2pi(x)

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

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

Note

Depending on the format of the input value, the closest representable value to 2π may be less than 2π. For example, the expression mod2pi(2π) will not return 0, because the intermediate value of 2*π is a Float64 and 2*Float64(π) < 2*big(π). See rem2pi for more refined control of this behavior.

Examples

julia> mod2pi(9*pi/4)
0.7853981633974481
source
Base.mod1 — Function
mod1(x, y)

Equivalent to rem(x, y, RoundUp) + x*sign(y). Returns a value in the range $(0, y]$ for positive y and $[-|y|,0)$ for negative y.

With integer arguments and positive y, this is equal to mod(x, 1:y), and hence natural for 1-based indexing. By comparison, mod(x, y) == mod(x, 0:y-1) is natural for 0-based indexing.

See also rem, mod, cld, cldmod1.

Examples

julia> mod1(4, 2)
2

julia> [-7:7  mod1.(-7:7, 3)]'
2×15 adjoint(::Matrix{Int64}) with eltype Int64:
 -7  -6  -5  -4  -3  -2  -1  0  1  2  3  4  5  6  7
  2   3   1   2   3   1   2  3  1  2  3  1  2  3  1

julia> 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.divrem — Function
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 of r, this call is equivalent to (x ÷ y, x % y).

See also fldmod, cldmod1, div, rem.

Examples

julia> divrem(3, 7)
(0, 3)

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

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

See also fld, mod, divrem, cldmod1.

source
Base.cldmod1 — Function
cldmod1(x, y)

Return (cld(x,y), mod1(x,y)). For positive integer inputs, this is the (col, row) index of the xᵗʰ element in a column major matrix with y rows.

See also cld, mod1, divrem, fldmod.

Examples

julia> col, row = cldmod1(20, 6)
(4, 2)

julia> 20 == (col - 1) * 6 + row
true

julia> reshape(1:36, 6, 6)
6×6 reshape(::UnitRange{Int64}, 6, 6) with eltype Int64:
 1   7  13  19  25  31
 2   8  14  20  26  32
 3   9  15  21  27  33
 4  10  16  22  28  34
 5  11  17  23  29  35
 6  12  18  24  30  36
source
Base.:// — Function
//(num, den)

Divide two integers or rational numbers, giving a Rational 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 of Integer, Rational, or composites thereof.

Examples

julia> 3 // 5
3//5

julia> (3 // 5) // (2 // 1)
3//10

julia> (1+2im) // (3+4im)
11//25 + 2//25*im

julia> 1.0 // 2
ERROR: MethodError: no method matching //(::Float64, ::Int64)
[...]
source
Base.rationalize — Function
rationalize([T<:Integer=Int,] x; tol::Real=eps(x))

Approximate floating point number x as a Rational number with components of the given integer type. The result will differ from x by no more than tol.

Examples

julia> rationalize(5.6)
28//5

julia> a = rationalize(BigInt, 10.3)
103//10

julia> typeof(numerator(a))
BigInt
source
Base.numerator — Function
numerator(x)

Numerator of the rational representation of x.

Examples

julia> numerator(2//3)
2

julia> numerator(4)
4
source
Base.denominator — Function
denominator(x)

Denominator of the rational representation of x.

Examples

julia> denominator(2//3)
3

julia> denominator(4)
1
source

Comparisons

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 and NaN != NaN.

The result is of type Bool, except when one of the operands is missing, in which case missing is returned (three-valued logic). Collections generally implement three-valued logic akin to all, returning missing if any operands contain missing values and all other pairs are equal. Use isequal or === to always get a Bool 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.

Equality and hashing are intimately related; two values that are considered isequal must have the same hash and by default isequal falls back to ==. If a type customizes the behavior of == and/or isequal, then hash must be similarly implemented to ensure isequal and hash agree. Sets, Dicts, and many other internal implementations assume that this invariant holds.

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

source
Base.:!= — Function
!=(x)

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

Julia 1.2

This functionality requires at least Julia 1.2.

source
!=(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 != 2
true

julia> "foo" ≠ "foo"
false
source
Core.:!== — Function
!==(x, y)
≢(x,y)

Always gives the opposite answer as ===.

Examples

julia> a = [1, 2]; b = [1, 2];

julia> a ≢ b
true

julia> a ≢ a
false
source
Base.:< — Function
<(x)

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

Julia 1.2

This functionality requires at least Julia 1.2.

source
<(x, y)

Less-than comparison operator. Falls back to isless. 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 implement isless instead.

See also isunordered.

Examples

julia> 'a' < 'b'
true

julia> "abc" < "abd"
true

julia> 5 < 3
false
source
Base.:<= — Function
<=(x)

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

Julia 1.2

This functionality requires at least Julia 1.2.

source
<=(x, y)
≤(x,y)

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

Examples

julia> 'a' <= 'b'
true

julia> 7 ≤ 7 ≤ 9
true

julia> "abc" ≤ "abc"
true

julia> 5 <= 3
false
source
Base.:> — Function
>(x)

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

Julia 1.2

This functionality requires at least Julia 1.2.

source
>(x, y)

Greater-than comparison operator. Falls back to y < 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'
false

julia> 7 > 3 > 1
true

julia> "abc" > "abd"
false

julia> 5 > 3
true
source
Base.:>= — Function
>=(x)

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

Julia 1.2

This functionality requires at least Julia 1.2.

source
>=(x, y)
≥(x,y)

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

Implementation

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

Furthermore, in many cases it is enough to implement just < and ==, relying on the fallback definitions of both <= and >=.

Examples

julia> 'a' >= 'b'
false

julia> 7 ≥ 7 ≥ 3
true

julia> "abc" ≥ "abc"
true

julia> 5 >= 3
true
source
Base.cmp — Function
cmp(a::AbstractString, b::AbstractString)::Int

Compare two strings. Return 0 if both strings have the same length and the character at each index is the same in both strings. Return -1 if a is a prefix of b, or if a comes before b in alphabetical order. Return 1 if b is a prefix of a, or if b comes before a in alphabetical order (technically, lexicographical order by Unicode code points).

Examples

julia> cmp("abc", "abc")
0

julia> cmp("ab", "abc")
-1

julia> cmp("abc", "ab")
1

julia> cmp("ab", "ac")
-1

julia> cmp("ac", "ab")
1

julia> cmp("α", "a")
1

julia> cmp("b", "β")
-1
source
cmp(<, x, y)

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

source
cmp(x,y)

Return -1, 0, or 1 depending on whether x is less than, equal to, or greater than y, respectively. Uses the total order implemented by isless.

Examples

julia> cmp(1, 2)
-1

julia> cmp(2, 1)
1

julia> cmp(2+im, 3-im)
ERROR: MethodError: no method matching isless(::Complex{Int64}, ::Complex{Int64})
[...]
source
Base.isapprox — Function
isapprox(x; kwargs...) / ≈(x; kwargs...)

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

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

Julia 1.5

This method requires Julia 1.5 or later.

source
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 distance or their absolute distance is within tolerance bounds: isapprox returns true if norm(x-y) <= max(atol, rtol*max(norm(x), norm(y))). The default atol (absolute tolerance) is zero and the default rtol (relative tolerance) depends on the types of x and y. The keyword argument nans determines whether or not NaN values are considered equal (defaults to false).

For real or complex floating-point values, if an atol > 0 is not specified, rtol defaults to the square root of eps of the type of x or y, 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 an atol > 0 is supplied, rtol defaults to zero.

The norm keyword defaults to abs for numeric (x,y) and to LinearAlgebra.norm for arrays (where an alternative norm choice is sometimes useful). When x and y are arrays, if norm(x-y) is not finite (i.e. ±Inf or NaN), the comparison falls back to checking whether all elements of x and y are approximately equal component-wise.

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

Note that x ≈ 0 (i.e., comparing to zero with the default tolerances) is equivalent to x == 0 since the default atol is 0. In such cases, you should either supply an appropriate atol (or use norm(x) ≤ atol) or rearrange your code (e.g. use x ≈ y rather than x - y ≈ 0). It is not possible to pick a nonzero atol automatically because it depends on the overall scaling (the "units") of your problem: for example, in x - y ≈ 0, atol=1e-9 is an absurdly small tolerance if x is the radius of the Earth in meters, but an absurdly large tolerance if x is the radius of a Hydrogen atom in meters.

Julia 1.6

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

Examples

julia> isapprox(0.1, 0.15; atol=0.05)
true

julia> isapprox(0.1, 0.15; rtol=0.34)
true

julia> isapprox(0.1, 0.15; rtol=0.33)
false

julia> 0.1 + 1e-10 ≈ 0.1
true

julia> 1e-10 ≈ 0
false

julia> isapprox(1e-10, 0, atol=1e-8)
true

julia> isapprox([10.0^9, 1.0], [10.0^9, 2.0]) # using `norm`
true
source

Logical Operators

Base.:! — Function
!f::Function

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

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 a ComposedFunction instead of an anonymous function.

source
!(x)

Boolean not. Implements three-valued logic, returning missing if x is missing.

See also ~ for bitwise not.

Examples

julia> !true
false

julia> !false
true

julia> !missing
missing

julia> .![true false true]
1×3 BitMatrix:
 0  1  0
source
&& — Keyword
x && y

Short-circuiting boolean AND.

This is equivalent to x ? y : false: it returns false if x is false and the result of evaluating y if x is true. Note that if y is an expression, it is only evaluated when x is true, which is called "short-circuiting" behavior.

Also, y does not need to have a boolean value. This means that (condition) && (statement) can be used as shorthand for if condition; statement; end for an arbitrary statement.

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

Examples

julia> x = 3;

julia> x > 1 && x < 10 && x isa Int
true

julia> x < 0 && error("expected positive x")
false

julia> x > 0 && "not a boolean"
"not a boolean"
source
|| — Keyword
x || y

Short-circuiting boolean OR.

This is equivalent to x ? true : y: it returns true if x is true and the result of evaluating y if x is false. Note that if y is an expression, it is only evaluated when x is false, which is called "short-circuiting" behavior.

Also, y does not need to have a boolean value. This means that (condition) || (statement) can be used as shorthand for if !(condition); statement; end for an arbitrary statement.

See also |, xor, &&.

Examples

julia> pi < 3 || ℯ < 3
true

julia> false || true || println("neither is true!")
true

julia> pi < 3 || "not a boolean"
"not a boolean"
source

Trigonometry

... in Radians

Base.sin — Method
sin(x::T) where {T <: Number} -> float(T)

Compute sine of x, where x is in radians.

Throw a DomainError if isinf(x), return a T(NaN) if isnan(x).

See also sind, 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.0

julia> sind(45)
0.7071067811865476

julia> sinpi(1/4)
0.7071067811865476

julia> round.(sincos(pi/6), digits=3)
(0.5, 0.866)

julia> round(cis(pi/6), digits=3)
0.866 + 0.5im

julia> round(exp(im*pi/6), digits=3)
0.866 + 0.5im
source
Base.Math.sincos — Method
sincos(x::T) where T -> Tuple{float(T),float(T)}

Simultaneously compute the sine and cosine of x, where x is in radians, returning a tuple (sine, cosine).

Throw a DomainError if isinf(x), return a (T(NaN), T(NaN)) if isnan(x).

See also cis, sincospi, sincosd.

source
Base.tan — Method
tan(x::T) where {T <: Number} -> float(T)

Compute tangent of x, where x is in radians.

Throw a DomainError if isinf(x), return a T(NaN) if isnan(x).

See also tanh.

source
Base.asin — Method
asin(x::T) where {T <: Number} -> float(T)

Compute the inverse sine of x, where the output is in radians.

Return a T(NaN) if isnan(x).

See also asind 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.acos — Method
acos(x::T) where {T <: Number} -> float(T)

Compute the inverse cosine of x, where the output is in radians.

Return a T(NaN) if isnan(x).

See also acosd for output in degrees.

source
Base.atan — Method
atan(y)
atan(y, x)

Compute the inverse tangent of y or y/x, respectively.

For one real argument, this is the angle in radians between the positive x-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 positive x-axis and the point (x, y), returning a value in the interval $[-\pi, \pi]$. This corresponds to a standard atan2 function. Note that by convention atan(0.0,x) is defined as $\pi$ and atan(-0.0,x) is defined as $-\pi$ when x < 0.

See also atand for degrees.

Examples

julia> rad2deg(atan(-1/√3))
-30.000000000000004

julia> rad2deg(atan(-1, √3))
-30.000000000000004

julia> rad2deg(atan(1, -√3))
150.0
source
Base.Math.sec — Method
sec(x::T) where {T <: Number} -> float(T)

Compute the secant of x, where x is in radians.

Throw a DomainError if isinf(x), return a T(NaN) if isnan(x).

source
Base.Math.csc — Method
csc(x::T) where {T <: Number} -> float(T)

Compute the cosecant of x, where x is in radians.

Throw a DomainError if isinf(x), return a T(NaN) if isnan(x).

source
Base.Math.cot — Method
cot(x::T) where {T <: Number} -> float(T)

Compute the cotangent of x, where x is in radians.

Throw a DomainError if isinf(x), return a T(NaN) if isnan(x).

source
Base.Math.asec — Method
asec(x::T) where {T <: Number} -> float(T)

Compute the inverse secant of x, where the output is in radians.

source
Base.Math.acsc — Method
acsc(x::T) where {T <: Number} -> float(T)

Compute the inverse cosecant of x, where the output is in radians.

source
Base.Math.acot — Method
acot(x::T) where {T <: Number} -> float(T)

Compute the inverse cotangent of x, where the output is in radians.

source

... in Degrees

Base.Math.sind — Function
sind(x::T) where T -> float(T)

Compute sine of x, where x is in degrees. If x is a matrix, x needs to be a square matrix.

Throw a DomainError if isinf(x), return a T(NaN) if isnan(x).

Julia 1.7

Matrix arguments require Julia 1.7 or later.

source
Base.Math.cosd — Function
cosd(x::T) where T -> float(T)

Compute cosine of x, where x is in degrees. If x is a matrix, x needs to be a square matrix.

Throw a DomainError if isinf(x), return a T(NaN) if isnan(x).

Julia 1.7

Matrix arguments require Julia 1.7 or later.

source
Base.Math.tand — Function
tand(x::T) where T -> float(T)

Compute tangent of x, where x is in degrees. If x is a matrix, x needs to be a square matrix.

Throw a DomainError if isinf(x), return a T(NaN) if isnan(x).

Julia 1.7

Matrix arguments require Julia 1.7 or later.

source
Base.Math.sincosd — Function
sincosd(x::T) where T -> Tuple{float(T),float(T)}

Simultaneously compute the sine and cosine of x, where x is in degrees, returning a tuple (sine, cosine).

Throw a DomainError if isinf(x), return a (T(NaN), T(NaN)) tuple if isnan(x).

Julia 1.3

This function requires at least Julia 1.3.

source
Base.Math.asind — Function
asind(x)

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

Julia 1.7

Matrix arguments require Julia 1.7 or later.

source
Base.Math.acosd — Function
acosd(x)

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

Julia 1.7

Matrix arguments require Julia 1.7 or later.

source
Base.Math.atand — Function
atand(y::T) where T -> float(T)
atand(y::T, x::S) where {T,S} -> promote_type(T,S)
atand(y::AbstractMatrix{T}) where T -> AbstractMatrix{Complex{float(T)}}

Compute the inverse tangent of y or y/x, respectively, where the output is in degrees.

Return a NaN if isnan(y) or isnan(x). The returned NaN is either a T in the single argument version, or a promote_type(T,S) in the two argument version.

Julia 1.7

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

source
Base.Math.secd — Function
secd(x::T) where {T <: Number} -> float(T)

Compute the secant of x, where x is in degrees.

Throw a DomainError if isinf(x), return a T(NaN) if isnan(x).

source
Base.Math.cscd — Function
cscd(x::T) where {T <: Number} -> float(T)

Compute the cosecant of x, where x is in degrees.

Throw a DomainError if isinf(x), return a T(NaN) if isnan(x).

source
Base.Math.cotd — Function
cotd(x::T) where {T <: Number} -> float(T)

Compute the cotangent of x, where x is in degrees.

Throw a DomainError if isinf(x), return a T(NaN) if isnan(x).

source
Base.Math.asecd — Function
asecd(x)

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

Julia 1.7

Matrix arguments require Julia 1.7 or later.

source
Base.Math.acscd — Function
acscd(x)

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

Julia 1.7

Matrix arguments require Julia 1.7 or later.

source
Base.Math.acotd — Function
acotd(x)

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

Julia 1.7

Matrix arguments require Julia 1.7 or later.

source

... in Multiples of π

Base.Math.tanpi — Function
tanpi(x::T) where T -> float(T)

Compute $\tan(\pi x)$ more accurately than tan(pi*x), especially for large x.

Throw a DomainError if isinf(x), return a T(NaN) if isnan(x).

Julia 1.10

This function requires at least Julia 1.10.

See also tand, sinpi, cospi, sincospi.

source
Base.Math.sincospi — Function
sincospi(x::T) where T -> Tuple{float(T),float(T)}

Simultaneously compute sinpi(x) and cospi(x) (the sine and cosine of π*x, where x is in radians), returning a tuple (sine, cosine).

Throw a DomainError if isinf(x), return a (T(NaN), T(NaN)) tuple if isnan(x).

Julia 1.6

This function requires Julia 1.6 or later.

See also cispi, sincosd, sinpi.

source

Hyperbolic

Base.tanh — Method
tanh(x)

Compute hyperbolic tangent of x.

See also tan, atanh.

Examples

julia> tanh.(-3:3f0)  # Here 3f0 isa Float32
7-element Vector{Float32}:
 -0.9950548
 -0.9640276
 -0.7615942
  0.0
  0.7615942
  0.9640276
  0.9950548

julia> tan.(im .* (1:3))
3-element Vector{ComplexF64}:
 0.0 + 0.7615941559557649im
 0.0 + 0.9640275800758169im
 0.0 + 0.9950547536867306im
source
Base.Math.sech — Method
sech(x::T) where {T <: Number} -> float(T)

Compute the hyperbolic secant of x.

Return a T(NaN) if isnan(x).

source
Base.Math.csch — Method
csch(x::T) where {T <: Number} -> float(T)

Compute the hyperbolic cosecant of x.

Return a T(NaN) if isnan(x).

source
Base.Math.coth — Method
coth(x::T) where {T <: Number} -> float(T)

Compute the hyperbolic cotangent of x.

Return a T(NaN) if isnan(x).

source
Base.Math.asech — Method
asech(x::T) where {T <: Number} -> float(T)

Compute the inverse hyperbolic secant of x.

source
Base.Math.acsch — Method
acsch(x::T) where {T <: Number} -> float(T)

Compute the inverse hyperbolic cosecant of x.

source
Base.Math.acoth — Method
acoth(x::T) where {T <: Number} -> float(T)

Compute the inverse hyperbolic cotangent of x.

source

Other Trigonometric Functions

Base.Math.sinc — Function
sinc(x::T) where {T <: Number} -> float(T)

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

Return a T(NaN) if isnan(x).

See also cosc, its derivative.

source
Base.Math.cosc — Function
cosc(x::T) where {T <: Number} -> float(T)

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

Return a T(NaN) if isnan(x).

See also sinc.

source
Base.Math.hypot — Function
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 for hypot(a,b) by Carlos F. Borges

hypot(x...)

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

See also norm in the LinearAlgebra standard library.

Examples

julia> a = Int64(10)^10;

julia> hypot(a, a)
1.4142135623730951e10

julia> √(a^2 + a^2) # a^2 overflows
ERROR: 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.0

julia> hypot(-5.7)
5.7

julia> hypot(3, 4im, 12.0)
13.0

julia> using LinearAlgebra

julia> norm([a, a, a, a]) == hypot(a, a, a, a)
true
source

Logarithms

Base.log — Method
log(x)

Compute the natural logarithm of x.

Throw a DomainError for negative Real arguments. Use Complex arguments to obtain Complex results.

Branch cut

log has a branch cut along the negative real axis; -0.0im is taken to be below the axis.

See also ℯ, exp, log1p, log2, log10.

Examples

julia> log(2)
0.6931471805599453

julia> 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.141592653589793im

julia> log(-3 - 0.0im)
1.0986122886681098 - 3.141592653589793im

julia> log.(exp.(-1:1))
3-element Vector{Float64}:
 -1.0
  0.0
  1.0
source
Base.log — Method
log(b,x)

Compute the base b logarithm of x. Throw a DomainError for negative Real arguments.

See also log2, log10.

Examples

julia> log(4,8)
1.5

julia> log(4,2)
0.5

julia> 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

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

julia> log(100,1000000)
2.9999999999999996

julia> log10(1000000)/2
3.0
source
Base.log2 — Function
log2(x)

Compute the logarithm of x to base 2. Throw a DomainError for negative Real arguments.

See also: exp2, log, ldexp, ispow2.

Examples

julia> log2(4)
2.0

julia> log2(10)
3.321928094887362

julia> 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.log10 — Function
log10(x)

Compute the logarithm of x to base 10. Throw a DomainError for negative Real arguments.

See also: exp10, log.

Examples

julia> log10(100)
2.0

julia> log10(2)
0.3010299956639812

julia> 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.log1p — Function
log1p(x)

Accurate natural logarithm of 1+x. Throw a DomainError for Real arguments less than -1.

Examples

julia> log1p(-0.5)
-0.6931471805599453

julia> log1p(0)
0.0

julia> 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

Exponentiation

Base.exp — Method
exp(x)

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

See also exp2, exp10, expm1, cis, log.

Examples

julia> exp(1.0)
2.718281828459045

julia> exp(im * pi) ≈ cis(pi)
true
source
Base.exp2 — Function
exp2(x)

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

See also exp, log2, ldexp, <<.

Examples

julia> exp2(5)
32.0

julia> 2^5
32

julia> exp2(63) > typemax(Int)
true
source
Base.exp10 — Function
exp10(x)

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

See also, exp, log10.

Examples

julia> exp10(2)
100.0

julia> 10^2
100
source
Base.expm1 — Function
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.

See also exp, log1p.

Examples

julia> expm1(1e-16)
1.0e-16

julia> exp(1e-16) - 1
0.0
source

Rounding

Base.round — Function
round([T,] x, [r::RoundingMode])
round(x, [r::RoundingMode]; digits::Integer=0, base = 10)
round(x, [r::RoundingMode]; sigdigits::Integer, base = 10)

Rounds the number x.

Without keyword arguments, x is rounded to an integer value, returning a value of type T, or of the same type of x if no T is provided. An InexactError will be thrown if the value is not representable by T, similar to convert.

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

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

The RoundingMode r controls the direction of the rounding; the default is RoundNearest, which rounds to the nearest integer, with ties (fractional values of 0.5) being rounded to the nearest even integer. Note that round may give incorrect results if the global rounding mode is changed (see rounding).

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 the floatmax(T) for purposes of determining "nearest", similar to convert.

Examples

julia> round(1.7)
2.0

julia> round(Int, 1.7)
2

julia> round(1.5)
2.0

julia> round(2.5)
2.0

julia> round(pi; digits=2)
3.14

julia> round(pi; digits=3, base=2)
3.125

julia> round(123.456; sigdigits=2)
120.0

julia> round(357.913; sigdigits=4, base=2)
352.0

julia> round(Float16, typemax(UInt128))
Inf16

julia> 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, the Float64 value represented by 1.15 is actually less than 1.15, yet will be rounded to 1.2. For example:

julia> x = 1.15
1.15

julia> big(1.15)
1.149999999999999911182158029987476766109466552734375

julia> x < 115//100
true

julia> round(x, digits=1)
1.2

Extensions

To extend round to new numeric types, it is typically sufficient to define Base.round(x::NewType, r::RoundingMode).

source
Base.Rounding.RoundNearest — Constant
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.RoundFromZero — Constant
RoundFromZero

Rounds away from zero.

Julia 1.9

RoundFromZero requires at least Julia 1.9. Prior versions support RoundFromZero for BigFloats only.

Examples

julia> BigFloat("1.0000000000000001", 5, RoundFromZero)
1.06
source
Base.round — Method
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-valued z to z, breaking ties using the specified RoundingModes. The first RoundingMode is used for rounding the real components while the second is used for rounding the imaginary components.

RoundingModeReal and RoundingModeImaginary default to RoundNearest, 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.0im

julia> round(3.14 + 4.5im, RoundUp, RoundNearestTiesUp)
4.0 + 5.0im

julia> round(3.14159 + 4.512im; digits = 1)
3.1 + 4.5im

julia> round(3.14159 + 4.512im; sigdigits = 3)
3.14 + 4.51im
source
Base.ceil — Function
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 as x that is greater than or equal to x.

ceil(T, x) converts the result to type T, throwing an InexactError if the ceiled value is not representable as a T.

Keywords digits, sigdigits and base work as for round.

To support ceil for a new type, define Base.round(x::NewType, ::RoundingMode{:Up}).

source
Base.floor — Function
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 as x that is less than or equal to x.

floor(T, x) converts the result to type T, throwing an InexactError if the floored value is not representable a T.

Keywords digits, sigdigits and base work as for round.

To support floor for a new type, define Base.round(x::NewType, ::RoundingMode{:Down}).

source
Base.trunc — Function
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 as x whose absolute value is less than or equal to the absolute value of x.

trunc(T, x) converts the result to type T, throwing an InexactError if the truncated value is not representable a T.

Keywords digits, sigdigits and base work as for round.

To support trunc for a new type, define Base.round(x::NewType, ::RoundingMode{:ToZero}).

See also: %, floor, unsigned, unsafe_trunc.

Examples

julia> trunc(2.22)
2.0

julia> trunc(-2.22, digits=1)
-2.2

julia> trunc(Int, -2.22)
-2
source
Base.unsafe_trunc — Function
unsafe_trunc(T, x)

Return the nearest integral value of type T whose absolute value is less than or equal to the absolute value of x. If the value is not representable by T, an arbitrary value will be returned. See also trunc.

Examples

julia> unsafe_trunc(Int, -2.2)
-2

julia> unsafe_trunc(Int, NaN) isa Int
true
source
Base.Math.modf — Function
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

Extrema

Base.min — Function
min(x, y, ...)

Return the minimum of the arguments, with respect to isless. If any of the arguments is missing, return missing. See also the minimum function to take the minimum element from a collection.

Examples

julia> min(2, 5, 1)
1

julia> min(4, missing, 6)
missing
source
Base.max — Function
max(x, y, ...)

Return the maximum of the arguments, with respect to isless. If any of the arguments is missing, return missing. See also the maximum function to take the maximum element from a collection.

Examples

julia> max(2, 5, 1)
5

julia> max(5, missing, 6)
missing
source
Base.minmax — Function
minmax(x, y)

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

See also extrema that returns (minimum(x), maximum(x)).

Examples

julia> minmax('c','b')
('b', 'c')
source

Clamping

Base.clamp — Function
clamp(x::Integer, r::AbstractUnitRange)

Clamp x to lie within range r.

Julia 1.6

This method requires at least Julia 1.6.

source
clamp(x, T)::T

Clamp x between typemin(T) and typemax(T) and convert the result to type T.

See also trunc.

Examples

julia> clamp(200, Int8)
127

julia> clamp(-200, Int8)
-128

julia> trunc(Int, 4pi^2)
39
source
clamp(x, lo, hi)

Return x if lo <= x <= hi. If x > hi, return hi. If x < lo, return lo. Arguments are promoted to a common type.

See also clamp!, 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.0

julia> clamp.([11, 8, 5], 10, 6)  # an example where lo > hi
3-element Vector{Int64}:
  6
  6
 10
source
Base.clamp! — Function
clamp!(array::AbstractArray, lo, hi)

Restrict values in array to the specified range, in-place. See also clamp.

Julia 1.3

missing entries in array 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  4

julia> 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

Checked Operations

Base.Checked — Module
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 like checked_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_abs — Function
Base.checked_abs(x)

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

The overflow protection may impose a perceptible performance penalty.

source
Base.Checked.checked_neg — Function
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_add — Function
Base.checked_add(x, y)

Calculates x+y, checking for overflow errors where applicable.

The overflow protection may impose a perceptible performance penalty.

source
Base.Checked.checked_sub — Function
Base.checked_sub(x, y)

Calculates x-y, checking for overflow errors where applicable.

The overflow protection may impose a perceptible performance penalty.

source
Base.Checked.checked_mul — Function
Base.checked_mul(x, y)

Calculates x*y, checking for overflow errors where applicable.

The overflow protection may impose a perceptible performance penalty.

source
Base.Checked.checked_div — Function
Base.checked_div(x, y)

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

The overflow protection may impose a perceptible performance penalty.

source
Base.Checked.checked_rem — Function
Base.checked_rem(x, y)

Calculates x%y, checking for overflow errors where applicable.

The overflow protection may impose a perceptible performance penalty.

source
Base.Checked.checked_fld — Function
Base.checked_fld(x, y)

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

The overflow protection may impose a perceptible performance penalty.

source
Base.Checked.checked_mod — Function
Base.checked_mod(x, y)

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

The overflow protection may impose a perceptible performance penalty.

source
Base.Checked.checked_cld — Function
Base.checked_cld(x, y)

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

The overflow protection may impose a perceptible performance penalty.

source
Base.Checked.checked_pow — Function
Base.checked_pow(x, y)

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

The overflow protection may impose a perceptible performance penalty.

source

Signs

Base.abs — Function
abs(x)

The absolute value of x.

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

See also: abs2, unsigned, sign.

Examples

julia> abs(-3)
3

julia> abs(1 + im)
1.4142135623730951

julia> abs.(Int8[-128 -127 -126 0 126 127])  # overflow at typemin(Int8)
1×6 Matrix{Int8}:
 -128  127  126  0  126  127

julia> maximum(abs, [1, -2, 3, -4])
4
source
Base.abs2 — Function
abs2(x)

Squared absolute value of x.

This can be faster than abs(x)^2, especially for complex numbers where abs(x) requires a square root via hypot.

See also abs, conj, real.

Examples

julia> abs2(-3)
9

julia> abs2(3.0 + 4.0im)
25.0

julia> sum(abs2, [1+2im, 3+4im])  # LinearAlgebra.norm(x)^2
30
source
Base.uabs — Function
Base.uabs(x::Integer)

Return the absolute value of x, possibly returning a different type should the operation be susceptible to overflow. This typically arises when x is a two's complement signed integer, so that abs(typemin(x)) == typemin(x) < 0, in which case the result of uabs(x) will be an unsigned integer of the same size.

source
Base.copysign — Function
copysign(x, y) -> z

Return z which has the magnitude of x and the same sign as y.

Examples

julia> copysign(1, -2)
-1

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

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

See also signbit, zero, copysign, flipsign.

Examples

julia> sign(-4.0)
-1.0

julia> sign(99)
1

julia> sign(-0.0)
-0.0

julia> sign(0 + im)
0.0 + 1.0im
source
Base.signbit — Function
signbit(x)

Return true if the value of the sign of x is negative, otherwise false.

See also sign, copysign.

Examples

julia> signbit(-4)
true

julia> signbit(5)
false

julia> signbit(5.5)
false

julia> signbit(-4.1)
true
source
Base.flipsign — Function
flipsign(x, y)

Return x with its sign flipped if y is negative. For example abs(x) = flipsign(x,x).

Examples

julia> flipsign(5, 3)
5

julia> flipsign(5, -3)
-5
source
Base.ispositive — Function
ispositive(x)

Test whether x > 0. See also isnegative.

Julia 1.13

This function requires at least Julia 1.13.

Examples

julia> ispositive(-4.0)
false

julia> ispositive(99)
true

julia> ispositive(0.0)
false
source
Base.isnegative — Function
isnegative(x)

Test whether x < 0. See also ispositive.

Julia 1.13

This function requires at least Julia 1.13.

Examples

julia> isnegative(-4.0)
true

julia> isnegative(99)
false

julia> isnegative(-0.0)
false
source

Roots

Base.sqrt — Method
sqrt(x)

Return $\sqrt{x}$.

Throw a DomainError for negative Real arguments. Use Complex negative arguments instead to obtain a Complex result.

The prefix operator √ is equivalent to sqrt.

Branch cut

sqrt has a branch cut along the negative real axis; -0.0im is taken to be below the axis.

See also cbrt, fourthroot, hypot.

Examples

julia> sqrt(big(81))
9.0

julia> 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.0im

julia> sqrt(-81 - 0.0im)  # -0.0im is below the branch cut
0.0 - 9.0im

julia> .√(1:4)
4-element Vector{Float64}:
 1.0
 1.4142135623730951
 1.7320508075688772
 2.0
source
Base.isqrt — Function
isqrt(n::Integer)

Integer square root: the largest integer m such that m*m <= n.

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

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

The prefix operator ∛ is equivalent to cbrt.

See also sqrt, fourthroot.

Examples

julia> cbrt(big(27))
3.0

julia> cbrt(big(-27))
-3.0
source

Complex Functions

Base.real — Function
real(A::AbstractArray)

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

Equivalent to real.(A), except that when eltype(A) <: Real A is returned without copying, and that when A 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
 3

julia> real(fill(2 - im))
0-dimensional Array{Int64, 0}:
2
source
real(T::Type)

Return the type that represents the real part of a value of type T. e.g., for T == Complex{R}, returns R. Equivalent to typeof(real(zero(T))).

Examples

julia> real(Complex{Int})
Int64

julia> real(Float64)
Float64
source
real(z)

Return the real part of the complex number z.

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

Examples

julia> real(1 + 3im)
1
source
Base.imag — Function
imag(A::AbstractArray)

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

Equivalent to imag.(A), except that when A 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
 4

julia> imag(fill(2 - im))
0-dimensional Array{Int64, 0}:
-1
source
imag(z)

Return the imaginary part of the complex number z.

See also conj, reim, adjoint, angle.

Examples

julia> imag(1 + 3im)
3
source
Base.reim — Function
reim(A::AbstractArray)

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

Equivalent to (real.(A), imag.(A)), except that when eltype(A) <: Real A is returned without copying to represent the real part, and that when A 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
reim(z)

Return a tuple of the real and imaginary parts of the complex number z.

Examples

julia> reim(1 + 3im)
(1, 3)
source
Base.conj — Function
conj(A::AbstractArray)

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

Equivalent to conj.(A), except that when eltype(A) <: Real A is returned without copying, and that when A 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 - 4im

julia> conj(fill(2 - im))
0-dimensional Array{Complex{Int64}, 0}:
2 + 1im
source
conj(z)

Compute the complex conjugate of a complex number z.

See also angle, adjoint.

Examples

julia> conj(1 + 3im)
1 - 3im
source
Base.angle — Function
angle(z)

Compute the phase angle in radians of a complex number z.

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.0

julia> rad2deg(angle(1 - im))
-45.0

julia> rad2deg(angle(-1 + 1e-20im))
180.0

julia> rad2deg(angle(-1 - 1e-20im))
-180.0
source
Base.cis — Function
cis(x)

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

See also cispi, sincos, exp, angle.

Examples

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

More accurate method for cis(pi*x) (especially for large x).

See also cis, sincospi, exp, angle.

Examples

julia> cispi(10000)
1.0 + 0.0im

julia> cispi(0.25 + 1im)
0.030556854645954562 + 0.03055685464595456im
Julia 1.6

This function requires Julia 1.6 or later.

source

Combinatorics and Number Theory

Base.binomial — Function
binomial(x::Number, k::Integer)

The generalized binomial coefficient, defined for k ≥ 0 by the polynomial

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

When k < 0 it returns zero.

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

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

Further generalizations to non-integer k 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 as SpecialFunctions.jl.

External links

source
binomial(n::Integer, k::Integer)

The binomial 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 choose k out of n items:

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

where $n!$ is the factorial 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 also factorial.

Examples

julia> binomial(5, 3)
10

julia> factorial(5) ÷ (factorial(5-3) * factorial(3))
10

julia> binomial(-5, 3)
-35

External links

source
Base.factorial — Function
factorial(n::Integer)

Factorial of n. If n is an Integer, the factorial is computed as an integer (promoted to at least 64 bits). Note that this may overflow if n is not small, but you can use factorial(big(n)) to compute the result exactly in arbitrary precision.

See also binomial.

Examples

julia> factorial(6)
720

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

julia> factorial(big(21))
51090942171709440000

External links

source
Base.gcd — Function
gcd(x, y...)

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

$a$ is a divisor of $b$ if there exists an integer $m$ such that $ma=b$.

Julia 1.4

Rational arguments require Julia 1.4 or later.

Examples

julia> gcd(6, 9)
3

julia> gcd(6, -9)
3

julia> gcd(6, 0)
6

julia> gcd(0, 0)
0

julia> gcd(1//3, 2//3)
1//3

julia> gcd(1//3, -2//3)
1//3

julia> gcd(1//3, 2)
1//3

julia> gcd(0, 0, 10, 15)
5
source
Base.lcm — Function
lcm(x, y...)

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

$a$ is a multiple of $b$ if there exists an integer $m$ such that $a=mb$.

Julia 1.4

Rational arguments require Julia 1.4 or later.

Examples

julia> lcm(2, 3)
6

julia> lcm(-2, 3)
6

julia> lcm(0, 3)
0

julia> lcm(0, 0)
0

julia> lcm(1//3, 2//3)
2//3

julia> lcm(1//3, -2//3)
2//3

julia> lcm(1//3, 2)
2//1

julia> lcm(1, 3, 5, 7)
105
source
Base.gcdx — Function
gcdx(a, b...)

Compute the greatest common (positive) divisor of a and b and their Bézout coefficients, i.e. the integer coefficients u and v that satisfy $u*a + v*b = d = gcd(a, b)$. $gcdx(a, b)$ returns $(d, u, v)$.

For more arguments than two, i.e., gcdx(a, b, c, ...) the Bézout coefficients are computed recursively, returning a solution (d, u, v, w, ...) to $u*a + v*b + w*c + ... = d = gcd(a, b, c, ...)$.

The arguments may be integer and rational numbers.

Julia 1.4

Rational arguments require Julia 1.4 or later.

Julia 1.12

More or fewer arguments than two require Julia 1.12 or later.

Examples

julia> gcdx(12, 42)
(6, -3, 1)

julia> gcdx(240, 46)
(2, -9, 47)

julia> gcdx(15, 12, 20)
(1, 7, -7, -1)
Note

Bézout coefficients are not 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 coefficients u and v are minimal in the sense that $|u| < |b/d|$ and $|v| < |a/d|$. Furthermore, the signs of u and v are chosen so that d is positive. For unsigned integers, the coefficients u and v might be near their typemax, and the identity then holds only via the unsigned integers' modulo arithmetic.

source
Base.ispow2 — Function
ispow2(n::Number)::Bool

Test whether n is an integer power of two.

See also count_ones, prevpow, nextpow.

Examples

julia> ispow2(4)
true

julia> ispow2(5)
false

julia> ispow2(4.5)
false

julia> ispow2(0.25)
true

julia> ispow2(1//8)
true
Julia 1.6

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

source
Base.nextpow — Function
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.

See also prevpow.

Examples

julia> nextpow(2, 7)
8

julia> nextpow(2, 9)
16

julia> nextpow(5, 20)
25

julia> nextpow(4, 16)
16
source
Base.prevpow — Function
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.

See also nextpow, isqrt.

Examples

julia> prevpow(2, 7)
4

julia> prevpow(2, 9)
8

julia> prevpow(5, 20)
5

julia> prevpow(4, 16)
16
source
Base.nextprod — Function
nextprod(factors::Union{Tuple,AbstractVector}, n)

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

Examples

julia> nextprod((2, 3), 105)
108

julia> 2^2 * 3^3
108
Julia 1.6

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

source
Base.invmod — Function
invmod(n::Integer, T) where {T <: Base.BitInteger}
invmod(n::T) where {T <: Base.BitInteger}

Compute the modular inverse of n in the integer ring of type T, i.e. modulo 2^N where N = 8*sizeof(T) (e.g. N = 32 for Int32). 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. This will throw an error if n is even, because then it is not relatively prime with 2^N and thus has no such inverse.

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 [An Improved Integer Modular Multiplicative Inverse (modulo $2^w$) by Jeffrey Hurchalla](https://arxiv.org/abs/2204.04342).

Julia 1.11

The invmod(n) and invmod(n, T) methods require Julia 1.11 or later.

source
invmod(n::Integer, m::Integer)

Take the inverse of n modulo m: 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)
3

julia> invmod(2, 3)
2

julia> invmod(5, 6)
5
source
Base.powermod — Function
powermod(x::Integer, p::Integer, m)

Compute $x^p \pmod m$.

Examples

julia> powermod(2, 6, 5)
4

julia> mod(2^6, 5)
4

julia> powermod(5, 2, 20)
5

julia> powermod(5, 2, 19)
6

julia> powermod(5, 3, 19)
11
source

Other Mathematical Functions

Base.add_sum — Function
Base.add_sum(x, y)

The reduction operator used in sum. The main difference from + is that small integers are promoted to Int/UInt.

source
Base.widemul — Function
widemul(x, y)

Multiply x and y, giving the result as a larger type.

See also promote, Base.add_sum.

Examples

julia> widemul(Float32(3.0), 4.0) isa BigFloat
true

julia> typemax(Int8) * typemax(Int8)
1

julia> widemul(typemax(Int8), typemax(Int8))  # == 127^2
16129
source
Base.Math.evalpoly — Function
evalpoly(x, p)

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

Julia 1.4

This function requires Julia 1.4 or later.

See also @evalpoly.

Examples

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

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

See also evalpoly.

Examples

julia> @evalpoly(3, 1, 0, 1)
10

julia> @evalpoly(2, 1, 0, 1)
5

julia> @evalpoly(2, 1, 1, 1)
7
source
Base.FastMath.@fastmath — Macro
@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 the LLVM Fast-Math flags, and corresponds to the -ffast-math option in clang. See [the notes on performance annotations](@ref man-performance-annotations) for more details.

Examples

julia> @fastmath 1+2
3

julia> @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 a binary operator using infix syntax: C = A ⊗ B as well as with the usual prefix syntax C = ⊗(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.