Numbers
Standard Numeric Types
Abstract number types
Core.Number
— Type.Number
Abstract supertype for all number types.
Core.Real
— Type.Real <: Number
Abstract supertype for all real numbers.
Core.AbstractFloat
— Type.AbstractFloat <: Real
Abstract supertype for all floating point numbers.
Core.Integer
— Type.Integer <: Real
Abstract supertype for all integers.
Core.Signed
— Type.Signed <: Integer
Abstract supertype for all signed integers.
Core.Unsigned
— Type.Unsigned <: Integer
Abstract supertype for all unsigned integers.
Concrete number types
Core.Float16
— Type.Float16 <: AbstractFloat
16-bit floating point number type.
Core.Float32
— Type.Float32 <: AbstractFloat
32-bit floating point number type.
Core.Float64
— Type.Float64 <: AbstractFloat
64-bit floating point number type.
Base.MPFR.BigFloat
— Type.BigFloat <: AbstractFloat
Arbitrary precision floating point number type.
Core.Bool
— Type.Bool <: Integer
Boolean type.
Core.Int8
— Type.Int8 <: Signed
8-bit signed integer type.
Core.UInt8
— Type.UInt8 <: Unsigned
8-bit unsigned integer type.
Core.Int16
— Type.Int16 <: Signed
16-bit signed integer type.
Core.UInt16
— Type.UInt16 <: Unsigned
16-bit unsigned integer type.
Core.Int32
— Type.Int32 <: Signed
32-bit signed integer type.
Core.UInt32
— Type.UInt32 <: Unsigned
32-bit unsigned integer type.
Core.Int64
— Type.Int64 <: Signed
64-bit signed integer type.
Core.UInt64
— Type.UInt64 <: Unsigned
64-bit unsigned integer type.
Core.Int128
— Type.Int128 <: Signed
128-bit signed integer type.
Core.UInt128
— Type.UInt128 <: Unsigned
128-bit unsigned integer type.
Base.GMP.BigInt
— Type.BigInt <: Integer
Arbitrary precision integer type.
Base.Complex
— Type.Complex{T<:Real} <: Number
Complex number type with real and imaginary part of type T
.
Complex32
, Complex64
and Complex128
are aliases for Complex{Float16}
, Complex{Float32}
and Complex{Float64}
respectively.
Base.Rational
— Type.Rational{T<:Integer} <: Real
Rational number type, with numerator and denominator of type T
.
Base.Irrational
— Type.Irrational <: Real
Irrational number type.
Data Formats
Base.bin
— Function.bin(n, pad::Int=1)
Convert an integer to a binary string, optionally specifying a number of digits to pad to.
julia> bin(10,2)
"1010"
julia> bin(10,8)
"00001010"
Base.hex
— Function.hex(n, pad::Int=1)
Convert an integer to a hexadecimal string, optionally specifying a number of digits to pad to.
julia> hex(20)
"14"
julia> hex(20, 3)
"014"
Base.dec
— Function.dec(n, pad::Int=1)
Convert an integer to a decimal string, optionally specifying a number of digits to pad to.
Examples
julia> dec(20)
"20"
julia> dec(20, 3)
"020"
Base.oct
— Function.oct(n, pad::Int=1)
Convert an integer to an octal string, optionally specifying a number of digits to pad to.
julia> oct(20)
"24"
julia> oct(20, 3)
"024"
Base.base
— Function.base(base::Integer, n::Integer, pad::Integer=1)
Convert an integer n
to a string in the given base
, optionally specifying a number of digits to pad to.
julia> base(13,5,4)
"0005"
julia> base(5,13,4)
"0023"
Base.digits
— Function.digits([T<:Integer], n::Integer, base::T=10, pad::Integer=1)
Returns an array with element type T
(default Int
) of the digits of n
in the given base, optionally padded with zeros to a specified size. More significant digits are at higher indexes, such that n == sum([digits[k]*base^(k-1) for k=1:length(digits)])
.
Examples
julia> digits(10, 10)
2-element Array{Int64,1}:
0
1
julia> digits(10, 2)
4-element Array{Int64,1}:
0
1
0
1
julia> digits(10, 2, 6)
6-element Array{Int64,1}:
0
1
0
1
0
0
Base.digits!
— Function.digits!(array, n::Integer, base::Integer=10)
Fills an array of the digits of n
in the given base. More significant digits are at higher indexes. If the array length is insufficient, the least significant digits are filled up to the array length. If the array length is excessive, the excess portion is filled with zeros.
Examples
julia> digits!([2,2,2,2], 10, 2)
4-element Array{Int64,1}:
0
1
0
1
julia> digits!([2,2,2,2,2,2], 10, 2)
6-element Array{Int64,1}:
0
1
0
1
0
0
Base.bits
— Function.bits(n)
A string giving the literal bit representation of a number.
Example
julia> bits(4)
"0000000000000000000000000000000000000000000000000000000000000100"
julia> bits(2.2)
"0100000000000001100110011001100110011001100110011001100110011010"
Base.parse
— Method.parse(type, str, [base])
Parse a string as a number. If the type is an integer type, then a base can be specified (the default is 10). If the type is a floating point type, the string is parsed as a decimal floating point number. If the string does not contain a valid number, an error is raised.
julia> parse(Int, "1234")
1234
julia> parse(Int, "1234", 5)
194
julia> parse(Int, "afc", 16)
2812
julia> parse(Float64, "1.2e-3")
0.0012
Base.tryparse
— Function.Base.big
— Function.Base.signed
— Function.signed(x)
Convert a number to a signed integer. If the argument is unsigned, it is reinterpreted as signed without checking for overflow.
Base.unsigned
— Function.unsigned(x) -> Unsigned
Convert a number to an unsigned integer. If the argument is signed, it is reinterpreted as unsigned without checking for negative values.
Examples
julia> unsigned(-2)
0xfffffffffffffffe
julia> unsigned(2)
0x0000000000000002
julia> signed(unsigned(-2))
-2
Base.float
— Method.float(x)
Convert a number or array to a floating point data type. When passed a string, this function is equivalent to parse(Float64, x)
.
Base.Math.significand
— Function.significand(x)
Extract the significand(s)
(a.k.a. mantissa), in binary representation, of a floating-point number. If x
is a non-zero finite number, then the result will be a number of the same type on the interval $[1,2)$. Otherwise x
is returned.
Examples
julia> significand(15.2)/15.2
0.125
julia> significand(15.2)*8
15.2
Base.Math.exponent
— Function.exponent(x) -> Int
Get the exponent of a normalized floating-point number.
Base.complex
— Method.complex(r, [i])
Convert real numbers or arrays to complex. i
defaults to zero.
Base.bswap
— Function.bswap(n)
Byte-swap an integer. Flip the bits of its binary representation.
Examples
julia> a = bswap(4)
288230376151711744
julia> bswap(a)
4
julia> bin(1)
"1"
julia> bin(bswap(1))
"100000000000000000000000000000000000000000000000000000000"
Base.num2hex
— Function.num2hex(f)
Get a hexadecimal string of the binary representation of a floating point number.
Example
julia> num2hex(2.2)
"400199999999999a"
Base.hex2num
— Function.hex2num(str)
Convert a hexadecimal string to the floating point number it represents.
Base.hex2bytes
— Function.hex2bytes(s::AbstractString)
Convert an arbitrarily long hexadecimal string to its binary representation. Returns an Array{UInt8,1}
, i.e. an array of bytes.
julia> a = hex(12345)
"3039"
julia> hex2bytes(a)
2-element Array{UInt8,1}:
0x30
0x39
Base.bytes2hex
— Function.bytes2hex(bin_arr::Array{UInt8, 1}) -> String
Convert an array of bytes to its hexadecimal representation. All characters are in lower-case.
julia> a = hex(12345)
"3039"
julia> b = hex2bytes(a)
2-element Array{UInt8,1}:
0x30
0x39
julia> bytes2hex(b)
"3039"
General Number Functions and Constants
Base.one
— Function.one(x)
one(T::type)
Return a multiplicative identity for x
: a value such that one(x)*x == x*one(x) == x
. Alternatively one(T)
can take a type T
, in which case one
returns a multiplicative identity for any x
of type T
.
If possible, one(x)
returns a value of the same type as x
, and one(T)
returns a value of type T
. However, this may not be the case for types representing dimensionful quantities (e.g. time in days), since the multiplicative identity must be dimensionless. In that case, one(x)
should return an identity value of the same precision (and shape, for matrices) as x
.
If you want a quantity that is of the same type as x
, or of type T
, even if x
is dimensionful, use oneunit
instead.
julia> one(3.7)
1.0
julia> one(Int)
1
julia> one(Dates.Day(1))
1
Base.oneunit
— Function.oneunit(x::T)
oneunit(T::Type)
Returns T(one(x))
, where T
is either the type of the argument or (if a type is passed) the argument. This differs from one
for dimensionful quantities: one
is dimensionless (a multiplicative identity) while oneunit
is dimensionful (of the same type as x
, or of type T
).
julia> oneunit(3.7)
1.0
julia> oneunit(Dates.Day)
1 day
Base.zero
— Function.zero(x)
Get the additive identity element for the type of x
(x
can also specify the type itself).
julia> zero(1)
0
julia> zero(big"2.0")
0.000000000000000000000000000000000000000000000000000000000000000000000000000000
julia> zero(rand(2,2))
2×2 Array{Float64,2}:
0.0 0.0
0.0 0.0
Base.pi
— Constant.pi
π
The constant pi.
julia> pi
π = 3.1415926535897...
Base.im
— Constant.im
The imaginary unit.
Base.eu
— Constant.e
eu
The constant e.
julia> e
e = 2.7182818284590...
Base.catalan
— Constant.catalan
Catalan's constant.
julia> catalan
catalan = 0.9159655941772...
Base.eulergamma
— Constant.γ
eulergamma
Euler's constant.
julia> eulergamma
γ = 0.5772156649015...
Base.golden
— Constant.φ
golden
The golden ratio.
julia> golden
φ = 1.6180339887498...
Base.Inf
— Constant.Inf
Positive infinity of type Float64
.
Base.Inf32
— Constant.Inf32
Positive infinity of type Float32
.
Base.Inf16
— Constant.Inf16
Positive infinity of type Float16
.
Base.NaN
— Constant.NaN
A not-a-number value of type Float64
.
Base.NaN32
— Constant.NaN32
A not-a-number value of type Float32
.
Base.NaN16
— Constant.NaN16
A not-a-number value of type Float16
.
Base.issubnormal
— Function.issubnormal(f) -> Bool
Test whether a floating point number is subnormal.
Base.isfinite
— Function.isfinite(f) -> Bool
Test whether a number is finite.
julia> isfinite(5)
true
julia> isfinite(NaN32)
false
Base.isinf
— Function.isinf(f) -> Bool
Test whether a number is infinite.
Base.isnan
— Function.isnan(f) -> Bool
Test whether a floating point number is not a number (NaN).
Base.iszero
— Function.iszero(x)
Return true
if x == zero(x)
; if x
is an array, this checks whether all of the elements of x
are zero.
Base.nextfloat
— Function.nextfloat(x::AbstractFloat, n::Integer)
The result of n
iterative applications of nextfloat
to x
if n >= 0
, or -n
applications of prevfloat
if n < 0
.
nextfloat(x::AbstractFloat)
Returns the smallest floating point number y
of the same type as x
such x < y
. If no such y
exists (e.g. if x
is Inf
or NaN
), then returns x
.
Base.prevfloat
— Function.prevfloat(x::AbstractFloat)
Returns the largest floating point number y
of the same type as x
such y < x
. If no such y
exists (e.g. if x
is -Inf
or NaN
), then returns x
.
Base.isinteger
— Function.isinteger(x) -> Bool
Test whether x
is numerically equal to some integer.
julia> isinteger(4.0)
true
Base.isreal
— Function.isreal(x) -> Bool
Test whether x
or all its elements are numerically equal to some real number.
julia> isreal(5.)
true
julia> isreal([4.; complex(0,1)])
false
Core.Float32
— Method.Float32(x [, mode::RoundingMode])
Create a Float32 from x
. If x
is not exactly representable then mode
determines how x
is rounded.
Examples
julia> Float32(1/3, RoundDown)
0.3333333f0
julia> Float32(1/3, RoundUp)
0.33333334f0
See RoundingMode
for available rounding modes.
Core.Float64
— Method.Float64(x [, mode::RoundingMode])
Create a Float64 from x
. If x
is not exactly representable then mode
determines how x
is rounded.
Examples
julia> Float64(pi, RoundDown)
3.141592653589793
julia> Float64(pi, RoundUp)
3.1415926535897936
See RoundingMode
for available rounding modes.
Base.GMP.BigInt
— Method.BigInt(x)
Create an arbitrary precision integer. x
may be an Int
(or anything that can be converted to an Int
). The usual mathematical operators are defined for this type, and results are promoted to a BigInt
.
Instances can be constructed from strings via parse
, or using the big
string literal.
julia> parse(BigInt, "42")
42
julia> big"313"
313
Base.MPFR.BigFloat
— Method.BigFloat(x)
Create an arbitrary precision floating point number. x
may be an Integer
, a Float64
or a BigInt
. The usual mathematical operators are defined for this type, and results are promoted to a BigFloat
.
Note that because decimal literals are converted to floating point numbers when parsed, BigFloat(2.1)
may not yield what you expect. You may instead prefer to initialize constants from strings via parse
, or using the big
string literal.
julia> BigFloat(2.1)
2.100000000000000088817841970012523233890533447265625000000000000000000000000000
julia> big"2.1"
2.099999999999999999999999999999999999999999999999999999999999999999999999999986
Base.Rounding.rounding
— Function.Base.Rounding.setrounding
— Method.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 may affect other types, for instance changing the rounding mode of Float64
will change the rounding mode of Float32
. See RoundingMode
for available modes.
This feature is still experimental, and may give unexpected or incorrect values.
Base.Rounding.setrounding
— Method.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.
This feature is still experimental, and may give unexpected or incorrect values. A known problem is the interaction with compiler optimisations, e.g.
julia> setrounding(Float64,RoundDown) do
1.1 + 0.1
end
1.2000000000000002
Here the compiler is constant folding, that is evaluating a known constant expression at compile time, however the rounding mode is only changed at runtime, so this is not reflected in the function result. This can be avoided by moving constants outside the expression, e.g.
julia> x = 1.1; y = 0.1;
julia> setrounding(Float64,RoundDown) do
x + y
end
1.2
Base.Rounding.get_zero_subnormals
— Function.get_zero_subnormals() -> Bool
Returns false
if operations on subnormal floating-point values ("denormals") obey rules for IEEE arithmetic, and true
if they might be converted to zeros.
Base.Rounding.set_zero_subnormals
— Function.set_zero_subnormals(yes::Bool) -> Bool
If yes
is false
, subsequent floating-point operations follow rules for IEEE arithmetic on subnormal values ("denormals"). Otherwise, floating-point operations are permitted (but not required) to convert subnormal inputs or outputs to zero. Returns true
unless yes==true
but the hardware does not support zeroing of subnormal numbers.
set_zero_subnormals(true)
can speed up some computations on some hardware. However, it can break identities such as (x-y==0) == (x==y)
.
Integers
Base.count_ones
— Function.count_ones(x::Integer) -> Integer
Number of ones in the binary representation of x
.
julia> count_ones(7)
3
Base.count_zeros
— Function.count_zeros(x::Integer) -> Integer
Number of zeros in the binary representation of x
.
julia> count_zeros(Int32(2 ^ 16 - 1))
16
Base.leading_zeros
— Function.leading_zeros(x::Integer) -> Integer
Number of zeros leading the binary representation of x
.
julia> leading_zeros(Int32(1))
31
Base.leading_ones
— Function.leading_ones(x::Integer) -> Integer
Number of ones leading the binary representation of x
.
julia> leading_ones(UInt32(2 ^ 32 - 2))
31
Base.trailing_zeros
— Function.trailing_zeros(x::Integer) -> Integer
Number of zeros trailing the binary representation of x
.
julia> trailing_zeros(2)
1
Base.trailing_ones
— Function.trailing_ones(x::Integer) -> Integer
Number of ones trailing the binary representation of x
.
julia> trailing_ones(3)
2
Base.isodd
— Function.isodd(x::Integer) -> Bool
Returns true
if x
is odd (that is, not divisible by 2), and false
otherwise.
julia> isodd(9)
true
julia> isodd(10)
false
Base.iseven
— Function.iseven(x::Integer) -> Bool
Returns true
is x
is even (that is, divisible by 2), and false
otherwise.
julia> iseven(9)
false
julia> iseven(10)
true
BigFloats
The BigFloat
type implements arbitrary-precision floating-point arithmetic using the GNU MPFR library.
Base.precision
— Function.precision(num::AbstractFloat)
Get the precision of a floating point number, as defined by the effective number of bits in the mantissa.
Base.precision
— Method.precision(BigFloat)
Get the precision (in bits) currently used for BigFloat
arithmetic.
Base.MPFR.setprecision
— Function.setprecision([T=BigFloat,] precision::Int)
Set the precision (in bits) to be used for T
arithmetic.
setprecision(f::Function, [T=BigFloat,] precision::Integer)
Change the T
arithmetic precision (in bits) for the duration of f
. It is logically equivalent to:
old = precision(BigFloat)
setprecision(BigFloat, precision)
f()
setprecision(BigFloat, old)
Often used as setprecision(T, precision) do ... end
Base.MPFR.BigFloat
— Method.BigFloat(x, prec::Int)
Create a representation of x
as a BigFloat
with precision prec
.
Base.MPFR.BigFloat
— Method.BigFloat(x, rounding::RoundingMode)
Create a representation of x
as a BigFloat
with the current global precision and rounding mode rounding
.
Base.MPFR.BigFloat
— Method.BigFloat(x, prec::Int, rounding::RoundingMode)
Create a representation of x
as a BigFloat
with precision prec
and rounding mode rounding
.
Base.MPFR.BigFloat
— Method.BigFloat(x::String)
Create a representation of the string x
as a BigFloat
.
Random Numbers
Random number generation in Julia uses the Mersenne Twister library via MersenneTwister
objects. Julia has a global RNG, which is used by default. Other RNG types can be plugged in by inheriting the AbstractRNG
type; they can then be used to have multiple streams of random numbers. Besides MersenneTwister
, Julia also provides the RandomDevice
RNG type, which is a wrapper over the OS provided entropy.
Most functions related to random generation accept an optional AbstractRNG
as the first argument, rng
, which defaults to the global one if not provided. Morever, some of them accept optionally dimension specifications dims...
(which can be given as a tuple) to generate arrays of random values.
A MersenneTwister
or RandomDevice
RNG can generate random numbers of the following types: Float16
, Float32
, Float64
, Bool
, Int8
, UInt8
, Int16
, UInt16
, Int32
, UInt32
, Int64
, UInt64
, Int128
, UInt128
, BigInt
(or complex numbers of those types). Random floating point numbers are generated uniformly in $[0, 1)$. As BigInt
represents unbounded integers, the interval must be specified (e.g. rand(big(1:6))
).
Base.Random.srand
— Function.srand([rng=GLOBAL_RNG], [seed]) -> rng
srand([rng=GLOBAL_RNG], filename, n=4) -> rng
Reseed the random number generator. If a seed
is provided, the RNG will give a reproducible sequence of numbers, otherwise Julia will get entropy from the system. For MersenneTwister
, the seed
may be a non-negative integer, a vector of UInt32
integers or a filename, in which case the seed is read from a file (4n
bytes are read from the file, where n
is an optional argument). RandomDevice
does not support seeding.
Base.Random.MersenneTwister
— Type.MersenneTwister(seed)
Create a MersenneTwister
RNG object. Different RNG objects can have their own seeds, which may be useful for generating different streams of random numbers.
Example
julia> rng = MersenneTwister(1234);
Base.Random.RandomDevice
— Type.RandomDevice()
Create a RandomDevice
RNG object. Two such objects will always generate different streams of random numbers.
Base.Random.rand
— Function.rand([rng=GLOBAL_RNG], [S], [dims...])
Pick a random element or array of random elements from the set of values specified by S
; S
can be
an indexable collection (for example
1:n
or['x','y','z']
), ora type: the set of values to pick from is then equivalent to
typemin(S):typemax(S)
for integers (this is not applicable toBigInt
), and to $[0, 1)$ for floating point numbers;
S
defaults to Float64
.
Base.Random.rand!
— Function.rand!([rng=GLOBAL_RNG], A, [coll])
Populate the array A
with random values. If the indexable collection coll
is specified, the values are picked randomly from coll
. This is equivalent to copy!(A, rand(rng, coll, size(A)))
or copy!(A, rand(rng, eltype(A), size(A)))
but without allocating a new array.
Example
julia> rng = MersenneTwister(1234);
julia> rand!(rng, zeros(5))
5-element Array{Float64,1}:
0.590845
0.766797
0.566237
0.460085
0.794026
Base.Random.bitrand
— Function.bitrand([rng=GLOBAL_RNG], [dims...])
Generate a BitArray
of random boolean values.
Example
julia> rng = MersenneTwister(1234);
julia> bitrand(rng, 10)
10-element BitArray{1}:
true
true
true
false
true
false
false
true
false
true
Base.Random.randn
— Function.randn([rng=GLOBAL_RNG], [T=Float64], [dims...])
Generate a normally-distributed random number of type T
with mean 0 and standard deviation 1. Optionally generate an array of normally-distributed random numbers. The Base
module currently provides an implementation for the types Float16
, Float32
, and Float64
(the default).
Examples
julia> rng = MersenneTwister(1234);
julia> randn(rng, Float64)
0.8673472019512456
julia> randn(rng, Float32, (2, 4))
2×4 Array{Float32,2}:
-0.901744 -0.902914 2.21188 -0.271735
-0.494479 0.864401 0.532813 0.502334
Base.Random.randn!
— Function.randn!([rng=GLOBAL_RNG], A::AbstractArray) -> A
Fill the array A
with normally-distributed (mean 0, standard deviation 1) random numbers. Also see the rand
function.
Example
julia> rng = MersenneTwister(1234);
julia> randn!(rng, zeros(5))
5-element Array{Float64,1}:
0.867347
-0.901744
-0.494479
-0.902914
0.864401
Base.Random.randexp
— Function.randexp([rng=GLOBAL_RNG], [T=Float64], [dims...])
Generate a random number of type T
according to the exponential distribution with scale 1. Optionally generate an array of such random numbers. The Base
module currently provides an implementation for the types Float16
, Float32
, and Float64
(the default).
Examples
julia> rng = MersenneTwister(1234);
julia> randexp(rng, Float32)
2.4835055f0
julia> randexp(rng, 3, 3)
3×3 Array{Float64,2}:
1.5167 1.30652 0.344435
0.604436 2.78029 0.418516
0.695867 0.693292 0.643644
Base.Random.randexp!
— Function.randexp!([rng=GLOBAL_RNG], A::AbstractArray) -> A
Fill the array A
with random numbers following the exponential distribution (with scale 1).
Example
julia> rng = MersenneTwister(1234);
julia> randexp!(rng, zeros(5))
5-element Array{Float64,1}:
2.48351
1.5167
0.604436
0.695867
1.30652
Base.Random.randjump
— Function.randjump(r::MersenneTwister, jumps::Integer, [jumppoly::AbstractString=dSFMT.JPOLY1e21]) -> Vector{MersenneTwister}
Create an array of the size jumps
of initialized MersenneTwister
RNG objects. The first RNG object given as a parameter and following MersenneTwister
RNGs in the array are initialized such that a state of the RNG object in the array would be moved forward (without generating numbers) from a previous RNG object array element on a particular number of steps encoded by the jump polynomial jumppoly
.
Default jump polynomial moves forward MersenneTwister
RNG state by 10^20
steps.