Modulo Division and Rounding
Base.mod — Function
rem(x::Integer, T::Type{<:Integer}) -> T
mod(x::Integer, T::Type{<:Integer}) -> T
%(x::Integer, T::Type{<:Integer}) -> TFind 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)
BigIntmod(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, and magnitude less than abs(y) (with some exceptions, see note below).
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, 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 2mod(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)
0Base.mod1 — Function
mod1(x, y)Modulus after flooring division, returning a value r such that mod(r, y) == mod(x, y) in the range $(0, y]$ for positive y and in the range $[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 computations with offsets or strides.
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.1Base.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π.
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.7853981633974481Base.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) == 1Note 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 https://arxiv.org/pdf/2204.04342.pdf.
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)
5Base.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 2Base.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 alsoRoundNearest.if
r == RoundToZero, then the result is in the interval $[0, 2π]$ ifxis positive,. or $[-2π, 0]$ otherwise. See alsoRoundToZero.if
r == RoundDown, then the result is in the interval $[0, 2π]$. See alsoRoundDown.if
r == RoundUp, then the result is in the interval $[-2π, 0]$. See alsoRoundUp.
Examples
julia> rem2pi(7pi/4, RoundNearest)
-0.7853981633974485
julia> rem2pi(7pi/4, RoundDown)
5.497787143782138Base.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 1Base.:÷ — 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 1Base.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).
Examples
julia> divrem(3, 7)
(0, 3)
julia> divrem(7, 3)
(2, 1)Base.fld — Function
fld(x, y)Largest integer less than or equal to x / y. Equivalent to div(x, y, RoundDown).
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 1Because fld(x, y) implements strictly correct floored rounding based on the true value of floating-point numbers, unintuitive situations can arise. For example:
julia> fld(6.0, 0.1)
59.0
julia> 6.0 / 0.1
60.0
julia> 6.0 / big(0.1)
59.99999999999999666933092612453056361837965690217069245739573412231113406246995What is happening here is that the true value of the floating-point number written as 0.1 is slightly larger than the numerical value 1/10 while 6.0 represents the number 6 precisely. Therefore the true value of 6.0 / 0.1 is slightly less than 60. When doing division, this is rounded to precisely 60.0, but fld(6.0, 0.1) always takes the floor of the true value, so the result is 59.0.
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)).
Base.fldmod1 — Function
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}).
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}).
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 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)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.2Extensions
To extend round to new numeric types, it is typically sufficient to define Base.round(x::NewType, r::RoundingMode).
Base.clamp — Function
clamp(x::Integer, r::AbstractUnitRange)Clamp x to lie within range r.
clamp(x, T)::TClamp 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)
39clamp(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.
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
10Base.clamp! — Function
clamp!(array::AbstractArray, lo, hi)Restrict values in array to the specified range, in-place. See also clamp.
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.0Roungding
Base.Rounding.rounding — Function
rounding(T)Get the current floating point rounding mode for type T, controlling the rounding of basic arithmetic functions (+, -, *, / and sqrt) and type conversion.
See RoundingMode for available modes.
Base.Rounding.setrounding — Function
setrounding(f::Function, T, mode)Change the rounding mode of floating point type T for the duration of f. It is logically equivalent to:
old = rounding(T)
setrounding(T, mode)
f()
setrounding(T, old)See RoundingMode for available rounding modes.
setrounding(T, mode)Set the rounding mode of floating point type T, controlling the rounding of basic arithmetic functions (+, -, *, / and sqrt) and type conversion. Other numerical functions may give incorrect or invalid values when using rounding modes other than the default RoundNearest.
Note that this is currently only supported for T == BigFloat.
RoundingMode
Base.Rounding.RoundingMode — Type
RoundingModeA 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:
Base.Rounding.RoundNearest — Constant
RoundNearestThe default rounding mode. Rounds to the nearest integer, with ties (fractional values of 0.5) being rounded to the nearest even integer.
Base.Rounding.RoundNearestTiesAway — Constant
RoundNearestTiesAwayRounds to nearest integer, with ties rounded away from zero (C/C++ round behaviour).
Base.Rounding.RoundNearestTiesUp — Constant
RoundNearestTiesUpRounds to nearest integer, with ties rounded toward positive infinity (Java/JavaScript round behaviour).
Base.Rounding.RoundToZero — Constant
Base.Rounding.RoundFromZero — Constant
RoundFromZeroRounds away from zero.
RoundFromZero requires at least Julia 1.9. Prior versions support RoundFromZero for BigFloats only.
Examples
julia> BigFloat("1.0000000000000001", 5, RoundFromZero)
1.06