Engee documentation

Mathematical objects

Mathematical operators

-(x)

The unary minus operator.

See also the description abs, flipsign.

Examples

julia> -1
-1

julia> -(2)
-2

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

julia> -(true)  # продвигается до Int
-1

julia> -(0x003)
0xfffd
dt::Date + t::Time -> DateTime

When adding the date (Date) and time (Time'), the total value of the date and time (`DateTime) is obtained. The components of hours, minutes, seconds, and milliseconds from the Time value are combined with the year, month, and day from the Date to form a new DateTime' value. If the `Time type contains non-zero values of micro- or nanoseconds, the error InexactError is returned.


+(x, y...)

The addition operator.

The infix expression 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 when adding large numbers, overflow is possible for most integer types, including the default Int type.

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
-(x, y)

The subtraction operator.

Examples

julia> 2 - 3
-1

julia> -(2, 4.5)
-2.5
*(x, y...)

The multiplication operator.

The infix expression 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.

When writing without a multiplication sign, for example 2pi, *(2, pi) is also called. Note that this operation has a higher priority than the literal *. Also note that writing unsigned numbers like "0x…​" (an integer zero multiplied by a variable whose name begins with x) is prohibited, as it conflicts with the literals of unsigned integers: `0x01 isa UInt8'.

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

Examples

julia> 2 * 7 * 8
112

julia> *(2, 7, 8)
112

julia> [2 0; 0 3] * [1, 10]  # матрица * вектор
2-element Vector{Int64}:
  2
 30

julia> 1/2pi, 1/2*pi  # умножение без знака имеет более высокий приоритет
(0.15915494309189535, 1.5707963267948966)

julia> x = [1, 2]; x'x  # сопряженный вектор * вектор
5
/(x, y)

Right division operator: Multiplies 'x` by the inverse of 'y` on the right side.

Returns a floating-point result for integer arguments. See description ÷ for integer division or // for results of the type Rational.

Examples

julia> 1/2
0.5

julia> 4/2
2.0

julia> 4.5/2
2.25

A / B

Right division of matrices: the expression A/B is equivalent to (B'\A')", where ` — left division operator. For square matrices, the result `X` will be such that A == X*B.

See also the description 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
\(x, y)

Left division operator: Multiplies y by the inverse of 'x` on the left side. Returns a floating-point result 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
^(x, y)

Exponentiation operator.

If x and y are integers, the result may overflow. To enter numbers in exponential representation, use literals. Float64, for example 1.2e3', and not `+1.2 * 10^3+.

If y is an integer (Int) literal (for example, 2 in the expression x^2 or -3 in x^-3), then the expression x^y in the Julia code is converted by the compiler to Base.literal_pow(^, x, Val(y)) to allow for specialization of the exponent value at compile time. (The default backup option is Base.literal_pow(^, x, Val(y)) = ^(x,y), where, as a rule, ^ == Base.^, unless ^ is specified in the namespace of the call.) If y is a negative integer literal, then Base.literal_pow by default converts the operation to inv(x)^-y, where the value -y is positive.

See also the description exp2 and <<.

Examples

julia> 3^5
243

julia> 3^-1  # использует 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
fma(x, y, z)

Calculates x*y+z without rounding the intermediate result x*y'. In some systems, this operation is significantly more expensive than `x*y+z'. The 'fma function is used to improve accuracy in some algorithms. See the description muladd.

muladd(x, y, z)

Combined Multiplication-addition: Calculates x*y+z, but allows you to combine addition and multiplication with each other or with neighboring operations to improve performance. For example, this can be implemented as fma if there is effective hardware support. It is possible to produce different results on different computers and even on the same computer due to constant substitution and other types of optimization. See the description fma.

Examples

julia> muladd(3, 2, 1)
7

julia> 3 * 2 + 1
7

muladd(A, y, z)

Combined multiplication-addition A*y .+ z for multiplying two matrices or a matrix and a vector. The result will always have the same size as A*y, but the value of z can be smaller or scalar.

Compatibility: Julia 1.6

These methods require a Julia version at least 1.6.

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
inv(x)

Returns the multiplicative inverse of x, so that x*inv(x) or inv(x)*x outputs one(x) (a single multiplication element) in the range of the rounding error.

If x is a number, the method is essentially the same as one(x)/x, however, 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
Compatibility: Julia 1.2

For inv(::Missing) requires a Julia version of at least 1.2.

div(x, y)
÷(x, y)

The result of Euclidean (integer) division. As a rule, it is equivalent to the result of the mathematical operation x/y without a fractional part.

See also the description 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
div(x, y, r::RoundingMode=RoundToZero)

The result of Euclidean (integer) division. Calculates x/y rounded to an integer in accordance with the rounding mode. In other words, the value of

round(x / y, r)

without any intermediate rounding.

Compatibility: Julia 1.4

A method with three arguments that accepts `RoundingMode' requires a Julia version of at least 1.4.

See also the description fld and cld, special cases of this function.

Compatibility: Julia 1.9

RoundFromZero requires a Julia version of at least 1.9.

Examples:

julia> div(4, 3, RoundToZero) # Совпадает с div(4, 3)
1
julia> div(4, 3, RoundDown) # Совпадает с fld(4, 3)
1
julia> div(4, 3, RoundUp) # Совпадает с 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
fld(x, y)

The largest integer that is less than or equal to `x/y'. Equivalent to `div(x, y, RoundDown)'.

See also the description div, cld and fld1.

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

Since fld(x,y) implements strict rounding down based on the true value of floating-point numbers, non-obvious situations may 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

In this case, the true value of the floating-point number written as 0.1 is slightly greater than the numeric value 1/10, while 6.0 exactly represents the number 6. Thus, the true value of 6.0 / 0.1 is slightly less than 60. When dividing, the result is rounded exactly to 60.0, however, fld(6.0, 0.1) always rounds the true value down, so the result will be `59.0'.

cld(x, y)

The smallest integer that is greater than or equal to `x/y'. Equivalent to `div(x, y, RoundUp)'.

See also the description div and fld.

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
mod(x::Integer, r::AbstractUnitRange)

Finds y in the range of r, so that , where n = length(r), i.e. y = mod(x - first(r), n) + first(r).

See also the description mod1.

Examples

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

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

This method requires a Julia version of 1.3 or higher.


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

The remainder of the integer division of x by y, equivalent to the remainder of the division of x by y with the result rounded down, i.e. x - y*fld(x,y) when calculated without intermediate rounding.

The sign of the result will be equal to the sign y, and its absolute value will be less than abs(y) (with some exceptions, see the note below).

When using floating-point values, it may not be possible to use this type to represent an accurate result, so rounding errors may occur. In particular, if the exact result is very close to y, it can be rounded to y.

See also the description rem, div, fld, mod1, 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

rem(x::Integer, T::Type{<:Integer}) -> T
mod(x::Integer, T::Type{<:Integer}) -> T
%(x::Integer, T::Type{<:Integer}) -> T

Finds y::T, so that xy (mod n), where n is the number of integers that can be represented in T, and y is an integer in [typemin(T),typemax(T)]. If 'T` can represent any integers (for example, T == BigInt), then the operation corresponds to the conversion to T.

Examples

julia> x = 129 % Int8
-127

julia> typeof(x)
Int8

julia> x = 129 % BigInt
129

julia> typeof(x)
BigInt
rem(x, y)
%(x, y)

The remainder of the Euclidean division, which returns a value with a sign equal to the sign of `x' and less modulo than `y'. This value is always accurate.

See also the description 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
rem(x, y, r::RoundingMode=RoundToZero)

Calculates the remainder of the integer division of x by y with rounding of the division result in r mode. In other words, the value of

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

without any intermediate rounding.

  • With r == RoundNearest, the result will be accurate and in the range of $[-

    y

    / 2,

    y

    / 2]$. See also the description RoundNearest.

  • With `r == RoundToZero' (default), the result will be accurate and in the range of $[0,

    y

    )$ with a positive x or $(-

    y

    , 0]$ otherwise. See also the description RoundToZero.

  • With r == RoundDown, the result will be in the range with a positive y or ] otherwise. The result may be inaccurate if x and y have different signs, and abs(x) < abs(y)'. See also the description `RoundDown.

  • With r == RoundUp, the result will be in the range ] with a positive y or otherwise. The result may be inaccurate if x and y have the same sign, and abs(x) < abs(y)'. See also the description `RoundUp.

  • With r == RoundFromZero, the result will be in the range ] with a positive y or otherwise. The result may be inaccurate if x and y have the same sign, and abs(x) < abs(y)'. See also the description `RoundFromZero.

Compatibility: Julia 1.9

RoundFromZero requires a Julia version of at least 1.9.

Examples:

julia> x = 9; y = 4;

julia> x % y  # то же, что и rem(x, y)
1

julia> x ÷ y  # то же, что и div(x, y)
2

julia> x == div(x, y) * y + rem(x, y)
true
rem2pi(x, r::RoundingMode)

Calculates the remainder of the integer division of x by with rounding of the division result in r mode. In other words, the value of

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

without any intermediate rounding. This function uses an internal high-precision approximation of 2π, so it gives a more accurate result than `rem(x,2π,r)'.

  • With r == RoundNearest, the result will be in the range ]. As a rule, this will be the most accurate result. See also the description RoundNearest.

  • With r == RoundToZero, the result will be in the range ] with a positive x or ] otherwise. See also the description RoundToZero.

  • With r == RoundDown, the result will be in the range ]. See also the description RoundDown.

  • With r == RoundUp, the result will be in the range ]. See also the description RoundUp.

Examples

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

julia> rem2pi(7pi/4, RoundDown)
5.497787143782138
mod2pi(x)

The remainder of the integer division by , returned in the range .

This function calculates the result as a floating-point number, which represents the remainder of the integer division by the numerically accurate value 2π'. Thus, it does not exactly match the function `mod(x,2π), which calculates the remainder of the integer division of x by the value , represented by a floating-point number.

Depending on the format of the input value, the nearest representable value for 2π may be less than 2π. For example, the expression mod2pi(2π) will not return 0, since the intermediate value 2*π is of type Float64, and 2*Float64(π) < 2*big(π). See function description rem2pi, which allows you to more precisely control this behavior.

Examples

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

The result and remainder of the Euclidean division. Equivalent to (div(x, y, r), rem(x, y, r)). With the default value for r` the call is equivalent to `(x ÷ y, x%y)'.

See also the description fldmod, cld.

Examples

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

julia> divrem(7, 3)
(2, 1)
fldmod(x, y)

The result and the remainder of the integer division with rounding down. It is a wrapper for convenience for divrem(x, y, RoundDown)'. Equivalent to `(fld(x, y), mod(x, y)).

See also the description fld, cld, fldmod1.

fld1(x, y)

Division with rounding down, which returns the value corresponding to mod1(x,y)

See also the description mod1 and fldmod1.

Examples

julia> x = 15; y = 4;

julia> fld1(x, y)
4

julia> x == fld(x, y) * y + mod(x, y)
true

julia> x == (fld1(x, y) - 1) * y + mod1(x, y)
true
mod1(x, y)

The remainder of the integer division with rounding down, returning the value of r, so that mod(r, y) == mod(x, y) in the range ] for a positive y and in the range for the negative `y'.

With integer arguments and a positive value of y, this is equal to mod(x, 1:y), which is naturally suitable for indexes starting with one. On the other hand, mod(x, y) == mod(x, 0:y-1) is suitable for calculations with offsets or array steps.

See also the description mod, fld1 and fldmod1.

Examples

julia> mod1(4, 2)
2

julia> mod1.(-5:5, 3)'
1×11 adjoint(::Vector{Int64}) with eltype Int64:
 1  2  3  1  2  3  1  2  3  1  2

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
fldmod1(x, y)

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

See also the description fld1 and mod1.

//(num, den)

Division of two integers or rational numbers, giving a result like Rational. More generally, // can be used for precise rational division of other numeric types with integer or rational components, such as complex numbers with integer components.

Note that the arguments are floating-point (AbstractFloat) are not allowed by the operator // (even if the values are rational). The types of arguments must be subtypes. Integer, Rational, or composite types based on them.

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)
[...]
rationalize([T<:Integer=Int,] x; tol::Real=eps(x))

Outputs the approximate value of the floating-point number x as a rational (Rational) numbers with components of the specified integer type. The result differs from x no more than it does from `tol'.

Examples

julia> rationalize(5.6)
28//5

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

julia> typeof(numerator(a))
BigInt
numerator(x)

The numerator of the rational representation is `x'.

Examples

julia> numerator(2//3)
2

julia> numerator(4)
4
denominator(x)

The denominator of the rational representation is `x'.

Examples

julia> denominator(2//3)
3

julia> denominator(4)
1
<<(x, n)

The bit shift operator to the left, x << n. For n >= 0, the result will be x with a left shift of n bits filled with zeros (0). This is equivalent to x*2^n. For n < 0, this is equivalent to x >> -n.

Examples

julia> Int8(3) << 2
12

julia> bitstring(Int8(3))
"00000011"

julia> bitstring(Int8(12))
"00001100"

See also the description >>, >>>, exp2 and ldexp.


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

The bit shift operator to the left, B << n. For n >= 0, the result will be B with the elements shifted by n positions in the opposite direction and filled with false values. If n < 0, the elements are shifted forward. Equivalent to B >> -n.

Examples

julia> B = BitVector([true, false, true, false, false])
5-element BitVector:
 1
 0
 1
 0
 0

julia> B << 1
5-element BitVector:
 0
 1
 0
 0
 0

julia> B << -1
5-element BitVector:
 0
 1
 0
 1
 0
>>(x, n)

The bit shift operator to the right, x >> n. For n >= 0, the result will be x with a right shift of n bits, and with a padding of 0 for x >= 0 or 1 for x < 0 while retaining the sign of x'. This is equivalent to `+fld(x, 2^n)+. For n < 0, this is equivalent to x << -n.

Examples

julia> Int8(13) >> 2
3

julia> bitstring(Int8(13))
"00001101"

julia> bitstring(Int8(3))
"00000011"

julia> Int8(-14) >> 2
-4

julia> bitstring(Int8(-14))
"11110010"

julia> bitstring(Int8(-4))
"11111100"

See also the description >>> and <<.


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

The bit shift operator to the right, B >> n. For n >= 0, the result will be B with the elements shifted forward by n positions and filled with false values. If n < 0, the elements are shifted in the opposite direction. Equivalent to B << -n.

Examples

julia> B = BitVector([true, false, true, false, false])
5-element BitVector:
 1
 0
 1
 0
 0

julia> B >> 1
5-element BitVector:
 0
 1
 0
 1
 0

julia> B >> -1
5-element BitVector:
 0
 1
 0
 0
 0
>>>(x, n)

The bit shift operator to the right is unsigned, x >>> n. For n >= 0, the result will be x with a right shift of n bits and filled with 0 values. For n < 0, this is equivalent to x << -n.

For unsigned integer types (Unsigned) this is equivalent to >>. For signed integer types (Signed) this is equivalent to `signed(unsigned(x) >> n)'.

Examples

julia> Int8(-14) >>> 2
60

julia> bitstring(Int8(-14))
"11110010"

julia> bitstring(Int8(60))
"00111100"

Type values BigInt are considered as having unlimited size, so no padding is required for them and it is equivalent to >>.

See also the description >> and <<.


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

The bit shift operator to the right is unsigned, B >>> n. Equivalent to B >> n. For more information and examples, see the description. >>.

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

The bitrotate(x, k) function implements a cyclic bit shift. It returns the value of x with its bits shifted to the left k' times. If the value of `k is negative, it shifts to the right instead.

Compatibility: Julia 1.5

This feature requires a Julia version of 1.5 or higher.

See also the description <<, circshift, BitArray.

julia> bitrotate(UInt8(114), 2)
0xc9

julia> bitstring(bitrotate(0b01110010, 2))
"11001001"

julia> bitstring(bitrotate(0b01110010, -2))
"10011100"

julia> bitstring(bitrotate(0b01110010, 8))
"01110010"
:expr

Encloses the expression expr in quotation marks, returning the abstract syntax tree (AST) expr'. An AST can have the type `Expr, Symbol, or be a literal value. The result of the syntax :identifier is a `Symbol'.

See also the description Expr, Symbol, Meta.parse

Examples

julia> expr = :(a = b + 2*x)
:(a = b + 2x)

julia> sym = :some_identifier
:some_identifier

julia> value = :0xff
0xff

julia> typeof((expr, sym, value))
Tuple{Expr, Symbol, UInt8}
range(start, stop, length)
range(start, stop; length, step)
range(start; length, stop, step)
range(;start, length, stop, step)

Creates a special array based on arguments with equidistant elements and optimized storage (AbstractRange). Mathematically, an array can be uniquely defined by any three of the following elements: start (start), step (step), end (stop) and length (length). Acceptable array calls:

  • Calling range with any three of the arguments start, step, stop, length.

  • Calling range with two of the arguments start, stop, length. In this case, step is assumed to be one. If both arguments are integers, it returns UnitRange.

  • Calling range with a single stop or length argument. The arguments start and step are assumed to be one.

For more information about the returned type, see the extended help. Also, see the function description. `logrange' for points with logarithmic intervals.

Examples

julia> range(1, length=100)
1:100

julia> range(1, stop=100)
1:100

julia> range(1, step=5, length=100)
1:5:496

julia> range(1, step=5, stop=100)
1:5:96

julia> range(1, 10, length=101)
1.0:0.09:10.0

julia> range(1, 100, step=5)
1:5:96

julia> range(stop=10, length=5)
6:10

julia> range(stop=10, step=1, length=5)
6:1:10

julia> range(start=1, step=1, stop=10)
1:1:10

julia> range(; length = 10)
Base.OneTo(10)

julia> range(; stop = 6)
Base.OneTo(6)

julia> range(; stop = 6.5)
1.0:1.0:6.0

If the length argument is not specified, and the stop - start value is not a multiple of the step value, a range ending before the 'stop` value will be created.

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

It is specially ensured that intermediate values are calculated rationally. This creates an additional computational burden. For information on how to avoid it, see the description of the constructor. LinRange.

Compatibility: Julia 1.1

To use stop as a positional argument, a version of Julia at least 1.1 is required.

Compatibility: Julia 1.7

Versions without named arguments and with a named start argument require a version of Julia at least 1.7.

Compatibility: Julia 1.8

Versions with a single named argument stop or length require a Julia version of at least 1.8.

Advanced Help

The range' function outputs `Base.OneTo when the arguments are integer and:

  • only the length argument is specified;

  • only the stop argument is specified.

The range' function outputs `UnitRange when the arguments are integer and:

  • only start and stop are specified;

  • only length and stop are specified.

If step is specified, even with a value of one, UnitRange is not issued.

Base.OneTo(n)

Defines the AbstractUnitRange range, acting as 1:n, for which the type system guarantees a lower bound of one.

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}

The range r, in which r[i] corresponds to values of type T (in the first form of the record, T is output automatically), with the parameters ref (reference value), step (step) and len' (length). By default, `ref is the initial value of r[1], but it can also be specified as the value of r[offset] for some other index 1 <= offset <= len. The syntax of a:b or a:b:c, where any of a, b or `c' is a floating point number, creates a `StepRangeLen'.

Compatibility: Julia 1.7

The 4th type parameter L requires a Julia version of at least 1.7.

logrange(start, stop, length)
logrange(start, stop; length)

Creates a special array, the elements of which are located at logarithmic intervals between the specified endpoints. That is, the ratio of consecutive elements is a constant calculated by length.

Similar to geomspace in Python. Unlike the PowerRange in Mathematica, you specify the number of elements, not the ratio. Unlike the logspace in Python and Matlab, the arguments start and stop are always the first and last elements of the result, rather than degrees applied to some base.

Examples

julia> logrange(10, 4000, length=3)
3-element Base.LogRange{Float64, Base.TwicePrecision{Float64}}:
 10.0, 200.0, 4000.0

julia> ans[2] ≈ sqrt(10 * 4000)  # средний элемент — это геометрическое среднее
true

julia> range(10, 40, length=3)[2] ≈ (10 + 40)/2  # арифметическое среднее
true

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

julia> logrange(1, 1000, length=4) ≈ 10 .^ (0:3)
true

For more information, see the type description. LogRange.

Also, see the function description. range for points with linear intervals.

Compatibility: Julia 1.11

This feature requires a version of Julia not lower than 1.11.

LogRange{T}(start, stop, len) <: AbstractVector{T}

The range, the elements of which are located with logarithmic intervals between start and stop', and the interval is determined by the argument `len. Returned by the function logrange.

As in the case of 'LinRange`, the first and last elements will exactly match the specified ones, but the intermediate values may have small floating-point errors. They are calculated using the logarithms of the endpoints, which are saved when the object is created, and often with higher accuracy than `T'.

Examples

julia> logrange(1, 4, length=5)
5-element Base.LogRange{Float64, Base.TwicePrecision{Float64}}:
 1.0, 1.41421, 2.0, 2.82843, 4.0

julia> Base.LogRange{Float16}(1, 4, 5)
5-element Base.LogRange{Float16, Float64}:
 1.0, 1.414, 2.0, 2.828, 4.0

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

julia> prevfloat(1e-308, 5) == ans[2]
true

Note that the integer element type T is not allowed. Use, for example, round.(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.0

julia> 2 .^ (0:3:9) |> println
[1, 8, 64, 512]
Compatibility: Julia 1.11

This type requires a Julia version not lower than 1.11.

==(x, y)

The universal equality operator. It uses as a backup option ===. It should be applied to all types that have the concept of equality, based on the abstract value represented by the instance. For example, all numeric types are compared by numeric value, regardless of type. Strings are compared as sequences of characters, regardless of encoding. Collections of the same type are usually compared by sets of keys, and if they are equal (==), then the values for each of the keys are compared. If all such pairs are equal (==), the value true is returned. Other properties (such as the exact type) are usually not taken into account.

The 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 (missing), and then the value missing' is returned (https://en.wikipedia.org/wiki/Three-valued_logic [ternary logic]). Collections usually implement ternary logic like `all: The missing value is returned if any operands contain missing values, and all other pairs are equal. To always get a Bool type result, use isequal or ===.

Implementation

New numeric types should have an implementation of this function to compare two arguments of the new type, and to compare with other types, if possible, apply promotion rules.

The '==` operator is used as a backup option for 'isequal`, so new == methods will be used to compare keys like Dict. If your type is going to be used as a dictionary key, it should also have an implementation. hash.

If == is defined for a type, isequal and isless, it must also have an implementation < for consistency of comparisons.

!=(x, y)
≠(x,y)

The comparison operator is "not equal". Always gives the opposite answer. ==.

Implementation

As a rule, the implementation of this operator is not required for new types, since instead they use the backup definition !=(x,y) = !(x==y).

Examples

julia> 3 != 2
true

julia> "foo" ≠ "foo"
false

!=(x)

Creates a function whose argument is compared to x via !=, i.e. a function equivalent to y -> y != x. The returned function is of type Base.Fix2{typeof(!=)} and can be used to implement specialized methods.

Compatibility: Julia 1.2

This feature requires a Julia version of at least 1.2.

!==(x, y)
≢(x,y)

Always gives the opposite answer. ===.

Examples

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

julia> a ≢ b
true

julia> a ≢ a
false
<(x, y)

The comparison operator is "less than". It uses as a backup option isless. Because of the way NaN floating-point values behave, this operator implements partial ordering.

Implementation

New numeric types with canonical partial order should implement this function to compare two arguments of the new type. Types with a canonical general order should instead have an implementation isless.

See also the description isunordered.

Examples

julia> 'a' < 'b'
true

julia> "abc" < "abd"
true

julia> 5 < 3
false

<(x)

Creates a function whose argument is compared to x via <, i.e. a function equivalent to y -> y < x. The returned function is of type Base.Fix2{typeof(<)} and can be used to implement specialized methods.

Compatibility: Julia 1.2

This feature requires a Julia version of at least 1.2.

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

The comparison operator is "less than or equal to". It uses (x < y) | (x ==y) as a backup option.

Examples

julia> 'a' <= 'b'
true

julia> 7 ≤ 7 ≤ 9
true

julia> "abc" ≤ "abc"
true

julia> 5 <= 3
false

<=(x)

Creates a function whose argument is compared to x via <=, i.e. a function equivalent to y -> y <=x. The returned function is of type Base.Fix2{typeof(<=)} and can be used to implement specialized methods.

Compatibility: Julia 1.2

This feature requires a Julia version of at least 1.2.

>(x, y)

The comparison operator is "more". It uses y < x as a backup option.

Implementation

As a rule, new types should use the implementation instead of this function. < and have a backup definition of >(x, y) = y < x.

Examples

julia> 'a' > 'b'
false

julia> 7 > 3 > 1
true

julia> "abc" > "abd"
false

julia> 5 > 3
true

>(x)

Creates a function whose argument is compared to x via >, i.e. a function equivalent to y -> y > x. The returned function is of type Base.Fix2{typeof(>)} and can be used to implement specialized methods.

Compatibility: Julia 1.2

This feature requires a Julia version of at least 1.2.

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

The comparison operator is "greater than or equal to". It uses y <=x as a backup option.

Examples

julia> 'a' >= 'b'
false

julia> 7 ≥ 7 ≥ 3
true

julia> "abc" ≥ "abc"
true

julia> 5 >= 3
true

>=(x)

Creates a function whose argument is compared to x via >=, i.e. a function equivalent to y -> y >=x. The returned function is of type Base.Fix2{typeof(>=)} and can be used to implement specialized methods.

Compatibility: Julia 1.2

This feature requires a Julia version of at least 1.2.

cmp(x,y)

Returns --1, 0, or 1, depending on whether the value of x is correspondingly less than, equal to, or greater than `y'. Uses the general 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})
[...]

cmp(<, x, y)

Returns --1, 0, or 1, depending on whether the value of x is correspondingly less than, equal to, or greater than `y'. The first argument indicates that the "less than" comparison function should be used.


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

Compares two strings. Returns 0 if both strings have the same length and all their characters match at each position. Returns -1 if a is a prefix of b or the characters in a are preceded by the characters of b in alphabetical order. Returns 1 if b is a prefix of a or the characters in b precede the characters of a in alphabetical order (strictly speaking, this is the lexicographic order by Unicode code positions).

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
~(x)

The bit "not".

See also the description !, &, |.

Examples

julia> ~4
-5

julia> ~10
-11

julia> ~true
false
x & y

Bitwise "and". Implements https://en.wikipedia.org/wiki/Three-valued_logic [ternary logic], returning missing if one of the operands is missing (missing) and the other is true (true). Use parentheses to apply the function form: (&)(x, y).

See also the description |, xor, &&.

Examples

julia> 4 & 10
0

julia> 4 & 12
4

julia> true & missing
missing

julia> false & missing
false
x | y

Bitwise "or". Implements https://en.wikipedia.org/wiki/Three-valued_logic [ternary logic], returning missing if one of the operands is missing (missing) and the other is true (false).

See also the description &, xor, ||.

Examples

julia> 4 | 10
14

julia> 4 | 1
5

julia> true | missing
true

julia> false | missing
missing
xor(x, y)
⊻(x, y)

The bit "exclusive or" for x and y. Implements https://en.wikipedia.org/wiki/Three-valued_logic [ternary logic], returning missing, if one of the arguments is missing (missing).

The infix operation a ⊻ b is synonymous with xor(a,b), and you can type using auto-completion on the TAB key for \xor or \veebar in REPL Julia.

Examples

julia> xor(true, false)
true

julia> xor(true, true)
false

julia> xor(true, missing)
missing

julia> false ⊻ false
false

julia> [true; true; false] .⊻ [true; false; false]
3-element BitVector:
 0
 1
 0
nand(x, y)
⊼(x, y)

Bit "and not" (nand) for x and y. Implements https://en.wikipedia.org/wiki/Three-valued_logic [ternary logic], returning missing, if one of the arguments is missing (missing).

The infix operation a ⊼ b is synonymous with nand(a,b), and you can type using auto-completion on the TAB key for \nand or \barwedge in REPL Julia.

Examples

julia> nand(true, false)
true

julia> nand(true, true)
false

julia> nand(true, missing)
missing

julia> false ⊼ false
true

julia> [true; true; false] .⊼ [true; false; false]
3-element BitVector:
 0
 1
 1
nor(x, y)
⊽(x, y)

Bit "or not" (nor) for x and y. Implements https://en.wikipedia.org/wiki/Three-valued_logic [ternary logic], returning missing, if one of the arguments is missing (missing) and the other is not (true).

The infix operation a ⊽ b is synonymous with nor(a,b), and you can type using auto-completion on the TAB key for \nor or \barvee in REPL Julia.

Examples

julia> nor(true, false)
false

julia> nor(true, true)
false

julia> nor(true, missing)
false

julia> false ⊽ false
true

julia> false ⊽ missing
missing

julia> [true; true; false] .⊽ [true; false; false]
3-element BitVector:
 0
 0
 1
!(x)

The logical "not". Implements https://en.wikipedia.org/wiki/Three-valued_logic [ternary logic], returning missing if x is missing (missing).

See also the description of the bit "not": .

Examples

julia> !true
false

julia> !false
true

julia> !missing
missing

julia> .![true false true]
1×3 BitMatrix:
 0  1  0

!f::Function

Negation of a predicative function: if the argument is ! is a function that returns a composite function that calculates the logical negation of f.

See also the description .

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: |-| <  ⇒ |()-()| < "
Compatibility: Julia 1.9

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

x && y

The logical "and" calculated according to the abbreviated scheme.

See also &, the ternary operator ? : and the section of the manual about order of execution.

Examples

julia> x = 3;

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

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

The logical "or" calculated according to the abbreviated scheme.

See also the description |, xor, &&.

Examples

julia> pi < 3 || ℯ < 3
true

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

Mathematical functions

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

An inaccurate equality comparison. Considers two numbers equal if the relative or absolute distance between them lies within the tolerance limits: 'isapprox` returns true if norm(x-y) <= max(atol, rtol*max(norm(x), norm(y)). The default value of atol' (absolute error) is zero, and the default value of `rtol (relative error) depends on the types x and y. The named argument nans determines whether to consider the NaN values equal (by default, false, i.e. no).

For real or complex floating point values, unless atol > 0 is specified, the default value of rtol' is the square root of `eps with type x or y', depending on which one is larger (lowest accuracy). In this case, approximately half of the significant characters must be equal. Otherwise, for example, for integer arguments or when specifying `atol > 0, the default value of rtol will be zero.

The named argument norm' defaults to `abs for numeric values (x,y) or LinearAlgebra.norm for arrays (where sometimes it makes sense to choose a different norm). When x and y are arrays, if the value is norm(x-y) If `x is not finite (i.e., ±Inf or NaN), then as a backup option, the comparison checks whether all elements x' and 'y are approximately equal in components.

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

Note that the expression x ≈ 0 (i.e., a comparison with zero with default tolerances) is equivalent to x == 0, since the default value of atol' is `0'. In such cases, you should either specify the desired value of `atol (or use norm(x) ≤ atol), or adjust the code (for example, use x ≈ y instead of x - y ≈ 0). Non-zero value of atol it cannot be selected automatically, since this value depends on the overall scale ("units") of the problem: for example, in the expression x - y ≈ 0, the error atol=1e-9 will be absurdly small if x represents https://en.wikipedia.org/wiki/Earth_radius [radius of the Earth] in meters, or absurdly large if x is https://en.wikipedia.org/wiki/Bohr_radius [radius of the hydrogen atom] in meters.

Compatibility: Julia 1.6

To pass the named norm argument when comparing numeric arguments (not arrays), a Julia version of at least 1.6 is required.

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]) # использование `norm`
true

isapprox(x; kwargs...) / ≈(x; kwargs...)

Creates a function whose argument is compared to x through , i.e. a function equivalent to y -> y ≈ x.

The same named arguments are supported as in the two-argument function `isapprox'.

Compatibility: Julia 1.5

This method requires a Julia version of 1.5 or higher.

sin(x)

Calculates the sine of 'x', where the value of x is given in radians.

See also the description 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.7071067811865475

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
cos(x)

Calculates the cosine of x', where the value of `x is given in radians.

See also the description cosd, cospi, sincos and cis.

sincos(x)

Simultaneously calculates the sine and cosine of x, where the value of x is set in radians, and returns the tuple (sine, cosine).

See also the description cis, sincospi and sincosd.

tan(x)

Calculates the tangent of x', where the value of `x is given in radians.

sind(x)

Calculates the sine of 'x', where the value of x is set in degrees. If 'x` is a matrix, then the matrix x must be square.

Compatibility: Julia 1.7

Matrix arguments require a Julia version of at least 1.7.

cosd(x)

Calculates the cosine of x', where the value of `x is set in degrees. If 'x` is a matrix, then the matrix x must be square.

Compatibility: Julia 1.7

Matrix arguments require a Julia version of at least 1.7.

tand(x)

Calculates the tangent of x', where the value of `x is set in degrees. If 'x` is a matrix, then the matrix x must be square.

Compatibility: Julia 1.7

Matrix arguments require a Julia version of at least 1.7.

sincosd(x)

Simultaneously calculates the sine and cosine of x, where the value of x is set in degrees.

Compatibility: Julia 1.3

This feature requires a Julia version of 1.3 or higher.

sinpi(x)

Calculates with more precision than `sin(pi*x)', especially for large values of `x'.

See also the description sind, cospi and sincospi.

cospi(x)

Calculates with more precision than `cos(pi*x)', especially for large values of `x'.

tanpi(x)

Calculates with more precision than `tan(pi*x)', especially for large values of `x'.

Compatibility: Julia 1.10

This feature requires a version of Julia at least 1.10.

See also the description tand, sinpi, cospi and sincospi.

sincospi(x)

Simultaneously calculates sinpi(x) and cospi(x) (the sine and cosine of π*x, where the value of x is given in radians) and returns the tuple (sine, cosine).

Compatibility: Julia 1.6

This feature requires a Julia version of at least 1.6.

See also the description cispi, sincosd, sinpi.

sinh(x)

Calculates the hyperbolic sine of `x'.

cosh(x)

Calculates the hyperbolic cosine of `x'.

tanh(x)

Calculates the hyperbolic tangent of `x'.

See also the description tan and atanh.

Examples

julia> tanh.(-3:3f0)  # Здесь 3f0 является 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
asin(x)

Calculates the arcsin of x with an output value in radians.

Also, see the function description. asind, which calculates the output values 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)
acos(x)

Calculates the arccosine of x with an output value in radians.

atan(y)
atan(y, x)

Calculates the arctangent y or y/x, respectively.

If there is one real argument, it will be the angle in radians between the positive direction of the x axis and the point (1, y). The return value will be in the range ].

If there are two arguments, this will be the angle in radians between the positive direction of the x axis and the point (x, y). The return value will be in the range ]. This corresponds to the standard function https://en.wikipedia.org/wiki/Atan2 [atan2]. Note that according to the standard, atan(0.0,x) is defined as , and atan(-0.0,x) — as for x < 0.

See also the description 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
asind(x)

Calculates the arcsin of x with the output value in degrees. If 'x` is a matrix, then the matrix x must be square.

Compatibility: Julia 1.7

Matrix arguments require a Julia version of at least 1.7.

acosd(x)

Calculates the arccosine of x with an output value in degrees. If 'x` is a matrix, then the matrix x must be square.

Compatibility: Julia 1.7

Matrix arguments require a Julia version of at least 1.7.

atand(y)
atand(y,x)

Calculates the arctangent of y or y/x respectively with the output value in degrees.

Compatibility: Julia 1.7

The single-argument method supports a square matrix as an argument starting with version Julia 1.7.

sec(x)

Calculates the x second, where the value of x is set in radians.

csc(x)

Calculates the cosecance of x', where the value of `x is given in radians.

cot(x)

Calculates the cotangent of x', where the value of `x is given in radians.

secd(x)

Calculates the x section, where the value of x is set in degrees.

cscd(x)

Calculates the cosecance of x', where the value of `x is set in degrees.

cotd(x)

Calculates the cotangent of x, where the value of x is set in degrees.

asec(x)

Calculates the arcsecond x with an output value in radians.

acsc(x)

Calculates the arcsecond of x with an output value in radians.

acot(x)

Calculates the arc tangent x with an output value in radians.

asecd(x)

Calculates the arcsecond x with the output value in degrees. If 'x` is a matrix, then the matrix x must be square.

Compatibility: Julia 1.7

Matrix arguments require a Julia version of at least 1.7.

acscd(x)

Calculates the arcsecond x with the output value in degrees. If 'x` is a matrix, then the matrix x must be square.

Compatibility: Julia 1.7

The Julia version of at least 1.7 is required for matrix arguments.

acotd(x)

Calculates the arc tangent x with the output value in degrees. If 'x` is a matrix, then the matrix x must be square.

Compatibility: Julia 1.7

Matrix arguments require a Julia version of at least 1.7.

sech(x)

Calculates the hyperbolic second x.

csch(x)

Calculates the hyperbolic cosecance of `x'.

coth(x)

Calculates the hyperbolic cotangent of `x'.

asinh(x)

Calculates the hyperbolic arcsinus of `x'.

acosh(x)

Calculates the hyperbolic arccosine of `x'.

atanh(x)

Calculates the hyperbolic arctangent x.

asech(x)

Calculates the hyperbolic arcsecond x.

acsch(x)

Calculates the hyperbolic arcsecond x.

acoth(x)

Calculates the hyperbolic arc tangent x.

sinc(x)

Calculates the normalized sinc function by and by .

See also the derivative of this function cosc.

cosc(x)

Calculates by and by . This is the derivative of the function sinc(x).

See also the description sinc.

deg2rad(x)

Converts the value of x from degrees to radians.

See also the description rad2deg, sind and pi.

Examples

julia> deg2rad(90)
1.5707963267948966
rad2deg(x)

Converts the value of x from radians to degrees.

See also the description deg2rad.

Examples

julia> rad2deg(pi)
180.0
hypot(x, y)

Calculates the hypotenuse , avoiding overflow and going beyond the lower limit.

This code implements the algorithm from the article An Improved Algorithm for hypot(a,b) (Improved algorithm for hypot(a,b)) Carlos F. Borges. This article is available on the arXiv portal at the link https://arxiv.org/abs/1904.09481 .

hypot(x...)

Calculates the hypotenuse , avoiding overflow and going beyond the lower limit.

See also the norm function in the standard library. LinearAlgebra.

Examples

julia> a = Int64(10)^10;

julia> hypot(a, a)
1.4142135623730951e10

julia> √(a^2 + a^2) # Возникает переполнение a^2
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
log(x)

Calculates the natural logarithm of `x'.

Returns an error DomainError for negative arguments of the type Real. Use complex arguments to get complex results. It has a branching point on the negative real axis, so -0.0im is assumed to be located below the axis.

See also the description , log1p, log2 and 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
log(b,x)

Calculates the logarithm of x based on b. Returns an error DomainError for negative arguments of the type Real.

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
[...]

If b is a power of 2 or 10, you should use log2 or log10, as these functions will generally be faster and more accurate. Example:

julia> log(100,1000000)
2.9999999999999996
julia> log10(1000000)/2 3.0
log2(x)

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

See also: exp2, 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
log10(x)

Calculates the logarithm of x based on 10. Returns an error DomainError for negative arguments of the type Real.

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
[...]
log1p(x)

The exact natural logarithm is 1+x'. Returns an error `DomainError for arguments of the type Real with a value 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
[...]
frexp(val)

Returns (x,exp) such that the absolute value of x lies in the range or is equal to zero, and val is equal to .

See also the description significand, exponent and ldexp.

Examples

julia> frexp(6.0)
(0.75, 3)

julia> significand(6.0), exponent(6.0)  # вместо этого интервал [1, 2)
(1.5, 2)

julia> frexp(0.0), frexp(NaN), frexp(-Inf)  # экспонента даст ошибку
((0.0, 0), (NaN, 0), (-Inf, 0))
exp(x)

Calculates the exponent of x, i.e. .

See also the description exp2, exp10 and cis.

Examples

julia> exp(1.0)
2.718281828459045

julia> exp(im * pi) ≈ cis(pi)
true
exp2(x)

Calculates the exponentiation of 2 `x', i.e. .

See also the description ldexp and <<.

Examples

julia> exp2(5)
32.0

julia> 2^5
32

julia> exp2(63) > typemax(Int)
true
exp10(x)

Calculates the exponentiation of 10 to `x', i.e. .

Examples

julia> exp10(2)
100.0

julia> 10^2
100
ldexp(x, n)

Calculates .

See also the description frexp and exponent.

Examples

julia> ldexp(5.0, 2)
20.0
modf(x)

Returns the tuple (fpart, ipart) from the fractional and integer parts of the 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)
expm1(x)

Calculates it accurately . This avoids the loss of precision that occurs when calculating exp(x)-1 directly for small values of x.

Examples

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

julia> exp(1e-16) - 1
0.0
round([T,] x, [r::RoundingMode])
round(x, [r::RoundingMode]; digits::Integer=0, base = 10)
round(x, [r::RoundingMode]; sigdigits::Integer, base = 10)

Rounds up the number x.

If there are no named arguments, x is rounded to an integer value. Returns a value of type T if it is specified, or the same type as x if T is not specified. Returns an error InexactError, if it is impossible to represent a value with the type T, similar to the function convert.

If the named argument digits is specified, rounding to the specified number of decimal places (or to the decimal point if the argument value is negative) is performed based on base.

If the named argument sigdigits is specified, rounding to the specified number of significant digits based on `base' is performed.

The rounding direction is set by the argument RoundingMode r. By default, the rounding mode is used to the nearest integer. RoundNearest, in which fractional values of 0.5 are rounded to the nearest even integer. Note that 'round` may produce incorrect results if the global rounding mode is changed (see rounding).

Rounding to a floating-point type is performed to integers represented by this type (and Inf), and not to true integers. When determining the nearest value, Inf is considered as a value one unit of least precision (ulp) greater than floatmax(T), similarly 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)

When working with binary floating-point numbers, rounding to a specified number of digits based on a base other than 2 may be inaccurate. For example, a value like Float64, represented by the number 1.15, is actually _ less than_ 1.15, but it 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).

RoundingMode

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

Currently supported rounding modes are:

Compatibility: Julia 1.9

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

RoundNearest

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

RoundNearestTiesAway

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

RoundNearestTiesUp

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

RoundToZero

round using this rounding mode is an alias for trunc.

RoundFromZero

Rounds away from zero.

Compatibility: 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
RoundUp

In this rounding mode round is an alias for ceil.

RoundDown

In this rounding mode round is an alias for floor.

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

Returns the integer value closest to z of the same type as the complex value of z using the specified rounding modes RoundingMode for fractional values of 0.5. The first one `RoundingMode' is used for rounding real components, and the second one is used for imaginary ones.

For RoundingModeReal and RoundingModeImaginary', the default is `RoundNearest, rounding mode to the nearest integer, in which fractional values of 0.5 are 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
ceil([T,] x)
ceil(x; digits::Integer= [, base = 10])
ceil(x; sigdigits::Integer= [, base = 10])

The function ceil(x) returns the nearest integer value of the same type as x, which is greater than or equal to `x'.

The function 'ceil(T, x)` returns the result to the type T and returns the error InexactError if the limited value cannot be represented by the type T.

The named arguments digits, sigdigits and base' act in the same way as for `round.

For the new type to support ceil, define Base.round(x::NewType, ::RoundingMode{:Up}).

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

The function floor(x) returns the nearest integer value of the same type as x, which is less than or equal to `x'.

The function floor(T, x) returns the result to the type T and returns the error InexactError if the limited value cannot be represented by the type T.

The named arguments digits, sigdigits and base' act in the same way as for `round.

For the new type to support floor, define Base.round(x::NewType, ::RoundingMode{:Down}).

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

The function trunc(x) returns the nearest integer value of the same type as x, the absolute value of which does not exceed the absolute value of x.

The function trunc(T, x) returns the result to the type T and returns the error InexactError if the truncated value cannot be represented by the type T.

The named arguments digits, sigdigits and base' act in the same way as for `round.

For the new type to support trunk, define Base.round(x::NewType, ::RoundingMode{:ToZero}).

See also the description %, 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
unsafe_trunc(T, x)

Returns the nearest integer value of type T, the absolute value of which does not exceed the absolute value of x'. If it is impossible to represent a value with the type `T, an arbitrary value is returned. See also the description trunc.

Examples

julia> unsafe_trunc(Int, -2.2)
-2

julia> unsafe_trunc(Int, NaN)
-9223372036854775808
min(x, y, ...)

Returns the lowest value among the arguments according to the criterion isless. If any of the arguments are missing (missing), returns missing'. See also function description `minimum, which gets the smallest item from the collection.

Examples

julia> min(2, 5, 1)
1

julia> min(4, missing, 6)
missing
max(x, y, ...)

Returns the largest value among the arguments according to the criterion isless. If any of the arguments are missing (missing), returns missing'. See also function description `maximum, which gets the largest item from the collection.

Examples

julia> max(2, 5, 1)
5

julia> max(5, missing, 6)
missing
minmax(x, y)

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

See also the function description extrema, which returns (minimum(x), maximum(x)).

Examples

julia> minmax('c','b')
('b', 'c')
clamp(x, lo, hi)

Returns x if lo <=x <= hi. For x > hi it returns hi. When x < lo returns lo. Arguments are promoted to a common type.

See also the description clamp!, min and max.

Compatibility: Julia 1.3

To use missing as the first argument, a version of Julia at least 1.3 is required.

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)  # Пример, в котором lo > hi.
3-element Vector{Int64}:
  6
  6
 10

clamp(x, T)::T

Brings x to the range between typemin(T) and typemax(T) and brings the result to type `T'.

See also the description trunc.

Examples

julia> clamp(200, Int8)
127

julia> clamp(-200, Int8)
-128

julia> trunc(Int, 4pi^2)
39

clamp(x::Integer, r::AbstractUnitRange)

Brings x to the range r.

Compatibility: Julia 1.6

This method requires a Julia version of at least 1.6.

clamp!(array::AbstractArray, lo, hi)

Brings each of the values of the array array to the specified range in place. See also the description clamp.

Compatibility: Julia 1.3

To use the missing elements in the array, a Julia version of at least 1.3 is required.

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
abs(x)

The absolute value of `x'.

When abs is applied to signed integers, overflow and negative value return are possible. Overflow occurs only when abs is applied to the minimum value that can be represented by a signed integer type, i.e. when x == typemin(typeof(x)), abs(x) == x < 0, not -x as one might expect.

See also the description abs2, unsigned, sign.

Examples

julia> abs(-3)
3

julia> abs(1 + im)
1.4142135623730951

julia> abs.(Int8[-128 -127 -126 0 126 127])  # переполнение при typemin(Int8)
1×6 Matrix{Int8}:
 -128  127  126  0  126  127

julia> maximum(abs, [1, -2, 3, -4])
4
Checked

The Checked module provides arithmetic functions for built-in signed and unsigned integer types that return an overflow error. They are called checked_sub', `checked_div', etc. In addition, `add_with_overflow', `sub_with_overflow', `mul_with_overflow return both unchecked results and a boolean value indicating the presence of overflow.

Base.checked_abs(x)

Calculates abs(x), checking for overflow errors, if applicable. For example, signed integers with a standard binary additional code (for example, Int) cannot represent abs(typemin(Int)), which causes overflow.

Overflow protection can lead to a noticeable decrease in performance.

Base.checked_neg(x)

Calculates -x', checking for overflow errors, if applicable. For example, signed integers with a standard binary additional code (for example, `Int) cannot represent -typemin(Int), which causes overflow.

Overflow protection can lead to a noticeable decrease in performance.

Base.checked_add(x, y)

Calculates `x+y', checking for overflow errors, if applicable.

Overflow protection can lead to a noticeable decrease in performance.

Base.checked_sub(x, y)

Calculates `x-y', checking for overflow errors, if applicable.

Overflow protection can lead to a noticeable decrease in performance.

Base.checked_mul(x, y)

Calculates `x*y', checking for overflow errors, if applicable.

Overflow protection can lead to a noticeable decrease in performance.

Base.checked_div(x, y)

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

Overflow protection can lead to a noticeable decrease in performance.

Base.checked_rem(x, y)

Calculates `x%y', checking for overflow errors, if applicable.

Overflow protection can lead to a noticeable decrease in performance.

Base.checked_fld(x, y)

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

Overflow protection can lead to a noticeable decrease in performance.

Base.checked_mod(x, y)

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

Overflow protection can lead to a noticeable decrease in performance.

Base.checked_cld(x, y)

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

Overflow protection can lead to a noticeable decrease in performance.

Base.checked_pow(x, y)

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

Overflow protection can lead to a noticeable decrease in performance.

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

Calculates r = x+y', and the `f flag indicates whether an overflow has occurred.

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

Calculates r = x-y', and the `f flag indicates whether an overflow has occurred.

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

Calculates r = x*y', and the `f flag indicates whether an overflow has occurred.

abs2(x)

The absolute value of `x' squared.

It may be faster than abs(x)^2, especially for complex numbers, where abs(x) requires getting the square root using hypot.

See also the description abs, conj and 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
copysign(x, y) -> z

Returns the value of z, modulo x with the sign `y'.

Examples

julia> copysign(1, -2)
-1

julia> copysign(-1, 2)
1
sign(x)

Returns zero if x==0, otherwise returns $x/

x

$ (i.e. ±1 for the real x).

See also the description signbit, zero, copysign and 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
signbit(x)

Returns true if the sign of x is negative, otherwise it returns `false'.

See also the description sign and copysign.

Examples

julia> signbit(-4)
true

julia> signbit(5)
false

julia> signbit(5.5)
false

julia> signbit(-4.1)
true
flipsign(x, y)

Returns x with the changed sign if the value of y is negative. For example, `abs(x) = flipsign(x,x)'.

Examples

julia> flipsign(5, 3)
5

julia> flipsign(5, -3)
-5
sqrt(x)

Returns .

Returns an error DomainError for negative arguments of the type Real. Use complex negative arguments instead. Note that the `sqrt' has a branch point on the negative real axis.

The prefix operator is equivalent to `sqrt'.

See also the description 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 находится ниже точки ветвления
0.0 - 9.0im

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

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

julia> isqrt(5)
2
cbrt(x::Real)

Returns the cubic root of `x', i.e. . It also accepts negative values (returns a negative real root when ).

The prefix operator is equivalent to cbrt.

Examples

julia> cbrt(big(27))
3.0

julia> cbrt(big(-27))
-3.0
real(z)

Returns the real part of the complex number z.

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

Examples

julia> real(1 + 3im)
1

real(T::Type)

Returns a type representing the real part of a value of type T'. For example, for `+T == Complex{R}+ returns R. Equivalent to `typeof(real(zero(T)))'.

Examples

julia> real(Complex{Int})
Int64

julia> real(Float64)
Float64

real(A::AbstractArray)

Returns an array containing the real part of each element in the array `A'.

Equivalent to real.(A) with the exception that when eltype(A) <: Real, the array A is returned without copying, and when A has zero dimension, a 0-dimensional array (and not a scalar value) is returned.

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
imag(z)

Returns the imaginary part of the complex number `z'.

See also the description conj, reim, adjoint, angle.

Examples

julia> imag(1 + 3im)
3

imag(A::AbstractArray)

Returns an array containing the imaginary part of each element in the array `A'.

Equivalent to imag.(A) with the exception that when array A has dimension zero, a 0-dimensional array is returned (rather than a scalar value).

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
reim(z)

Returns a tuple of the real and imaginary parts of the complex number `z'.

Examples

julia> reim(1 + 3im)
(1, 3)

reim(A::AbstractArray)

Returns a tuple of two arrays containing, respectively, the real and imaginary parts of each of the elements of `A'.

Equivalent to (real.(A), imag.(A))`with the exception that when `eltype(A) <: Real, the array A is returned without copying to represent the real part, and when A has zero dimension, a 0-dimensional array (and not a scalar value) is returned.

Examples

julia> reim([1, 2im, 3 + 4im])
([1, 0, 3], [0, 2, 4])

julia> reim(fill(2 - im))
(fill(2), fill(-1))
conj(z)

Calculates the conjugate complex number for the complex number `z'.

See also the description angle, adjoint.

Examples

julia> conj(1 + 3im)
1 - 3im

conj(A::AbstractArray)

Returns an array containing the conjugate complex number for each element in the array `A'.

Equivalent to conj.(A) with the exception that when eltype(A) <: Real, the array A is returned without copying, and when A has zero dimension, a 0-dimensional array (and not a scalar value) is returned.

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
angle(z)

Calculates the phase angle of the complex number z in radians.

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

See also the description 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
cis(x)

A more efficient method for exp(im*x) using Euler’s formula: .

See also the description cispi, sincos, exp and angle.

Examples

julia> cis(π) ≈ -1
true
cispi(x)

A more accurate method is for `cis(pi*x)' (especially for large values of `x').

See also the description cis, sincospi, exp and angle.

Examples

julia> cispi(10000)
1.0 + 0.0im

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

This feature requires a Julia version of at least 1.6.

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

binomial coefficient , representing the coefficient -th member in decomposition by polynomials.

If the value is non-negative, this coefficient shows how many ways it is possible to select k elements from the set of n:

where  — this is a function factorial.

If the value is If it is negative, the coefficient is defined as an identity

See also the description factorial.

Examples

julia> binomial(5, 3)
10

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

julia> binomial(-5, 3)
-35

External links


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

Generalized binomial coefficient defined for 'k ≥ 0` by a polynomial

When k < 0 returns zero.

For an integer x is equivalent to the usual integer binomial coefficient

Further generalizations for non-integer k are mathematically possible, but include a gamma function and/or a beta function, which are not provided by the Julia standard library, but are available in external packages such as https://github.com/JuliaMath/SpecialFunctions.jl [SpecialFunctions.jl].

External links

factorial(n::Integer)

The factorial is n'. If the value of `n is an integer (Integer), the factorial is calculated as an integer (advancing to at least 64-bit). Note that with a large value of n, overflow is possible, but you can use factorial(big(n)) to accurately calculate the result with arbitrary precision.

See also the description 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

gcd(x, y...)

The largest common (positive) divisor (or zero if all arguments are zero). Arguments can be integers or rational numbers.

Compatibility: Julia 1.4

Rational arguments require a Julia version of at least 1.4.

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
lcm(x, y...)

The smallest common (positive) multiple (or zero if one of the arguments is zero). Arguments can be integers or rational numbers.

Compatibility: Julia 1.4

Rational arguments require a Julia version of at least 1.4.

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
gcdx(a, b)

Calculates the largest common (positive) divisor of a and b, as well as their Bezoux coefficients, i.e. integer coefficients u and v satisfying the condition . returns .

Arguments can be integers or rational numbers.

Compatibility: Julia 1.4

Rational arguments require a Julia version of at least 1.4.

Examples

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

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

Bezu coefficients are not the only possible ones. The gcdx function returns the smallest Bezoux coefficients calculated using the extended Euclidean algorithm (see Knut D. The art of programming. Ed. 2. p. 325. Algorithm X). For signed integers, these coefficients u and v are the smallest in the sense that and . In addition, the signs u and v are selected so that the value of d is positive. For unsigned integers, the coefficients u and v can have values close to their typemax, and then the identity will be true only with modulo arithmetic for these unsigned integers.

ispow2(n::Number) -> Bool

Checks whether the number n is the result of raising 2 to an integer power.

See also the description count_ones, prevpow and 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
Compatibility: Julia 1.6

Support for arguments other than `Integer' was added in Julia 1.6.

nextpow(a, x)

The smallest value of a^n that is at least x', where `n is a non-negative integer. The value of 'a` must be greater than one, and x must be greater than zero.

See also the description prevpow.

Examples

julia> nextpow(2, 7)
8

julia> nextpow(2, 9)
16

julia> nextpow(5, 20)
25

julia> nextpow(4, 16)
16
prevpow(a, x)

The largest value is a^n, which is not greater than x, where n is a non-negative integer. The value of 'a` must be greater than one, and x must be at least one.

See also the description nextpow' and `isqrt.

Examples

julia> prevpow(2, 7)
4

julia> prevpow(2, 9)
8

julia> prevpow(5, 20)
5

julia> prevpow(4, 16)
16
nextprod(factors::Union{Tuple,AbstractVector}, n)

The next integer greater than or equal to n, which can be written as for integers , and so on for multipliers in `factors'.

Examples

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

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

A tuple-accepting method requires a Julia version of at least 1.6.

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

Takes the inverse of n modulo m, y, so that and . Returns an error if or .

Examples

julia> invmod(2, 5)
3

julia> invmod(2, 3)
2

julia> invmod(5, 6)
5

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

Calculates the modular inverse number n in the ring of integers of type T, i.e. modulo 2^N, where N = 8*sizeof(T) (for example, 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 a modular multiplication in the ring of integers `T'.

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

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

Compatibility: Julia 1.11

The methods invmod(n) and invmod(n, T) require a version of Julia not lower than 1.11.

powermod(x::Integer, p::Integer, m)

Calculates .

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
ndigits(n::Integer; base::Integer=10, pad::Integer=1)

Counts the number of digits in the whole number n written in the number system base (base cannot be in the range [-1, 0, 1]), if necessary, with the assignment of zeros (pad) to a given size (the result will never be less than pad).

See also the description digits and count_ones.

Examples

julia> ndigits(0)
1

julia> ndigits(12345)
5

julia> ndigits(1022, base=16)
3

julia> string(1022, base=16)
"3fe"

julia> ndigits(123, pad=5)
5

julia> ndigits(-123)
3
Base.add_sum(x, y)

The subtraction operator used in 'sum'. The main difference from + means that small integers advance to Int/`UInt'.

widemul(x, y)

Multiplies x and y, yielding a result with a larger type.

See also the description promote and 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
evalpoly(x, p)

Calculates the polynomial ] with coefficients p[1], p[2], …​; specified in ascending order by degree of x'. Loops are expanded at compile time if the number of coefficients is statically known, i.e. when `p is a tuple (Tuple). The function creates efficient code using the Horner method for the real value of x or an algorithm similar to the Herzel algorithm[Donald Knuth. The art of programming. Volume 2. Semi-numerical algorithms. Section 4.6.4.], if the value of x is complex.

Compatibility: Julia 1.4

This feature requires a Julia version of at least 1.4.

Examples

julia> evalpoly(2, (1, 2, 3))
17
@evalpoly(z, c...)

Calculates the polynomial ] with coefficients c[1], c[2], …​; indicated in ascending order by degree of z'. This macro is expanded into an efficient inline code using either the Horner method or, with a complex value of `z, a more efficient algorithm similar to the Goertzel algorithm.

See also the description evalpoly.

Examples

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

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

julia> @evalpoly(2, 1, 1, 1)
7
@fastmath expr

Executes a converted version of an expression that calls functions that may violate strict IEEE semantics. This ensures the fastest possible operation, but the results are uncertain. Use this with caution, as it is possible to change the numerical results.

The macro sets https://llvm.org/docs/LangRef.html#fast-math-flags [LLVM’s Fast-Math flags] and corresponds to the -ffast-math parameter in clang. For more information, see performance notes.

Examples

julia> @fastmath 1+2
3

julia> @fastmath(sin(3))
0.1411200080598672

Configurable 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 function (otimes) as a Kronecker product, and it can be called as a binary operator using the 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 .

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