Numbers¶
Standard Numeric Types¶
BoolInt8UInt8Int16UInt16Int32UInt32Int64UInt64Int128UInt128Float16Float32Float64Complex64Complex128
Data Formats¶
bin(n[, pad])¶Convert an integer to a binary string, optionally specifying a number of digits to pad to.
hex(n[, pad])¶Convert an integer to a hexadecimal string, optionally specifying a number of digits to pad to.
dec(n[, pad])¶Convert an integer to a decimal string, optionally specifying a number of digits to pad to.
oct(n[, pad])¶Convert an integer to an octal string, optionally specifying a number of digits to pad to.
base(base, n[, pad])¶Convert an integer to a string in the given base, optionally specifying a number of digits to pad to. The base can be specified as either an integer, or as a
UInt8array of character values to use as digit symbols.
digits(n[, base][, pad])¶Returns an array of the digits of
nin the given base, optionally padded with zeros to a specified size. More significant digits are at higher indexes, such thatn==sum([digits[k]*base^(k-1)fork=1:length(digits)]).
digits!(array, n[, base])¶Fills an array of the digits of
nin 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.
bits(n)¶A string giving the literal bit representation of a number.
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.
tryparse(type, str[, base])¶Like
parse, but returns aNullableof the requested type. The result will be null if the string does not contain a valid number.
big(x)¶Convert a number to a maximum precision representation (typically
BigIntorBigFloat). SeeBigFloatfor information about some pitfalls with floating-point numbers.
signed(x)¶Convert a number to a signed integer. If the argument is unsigned, it is reinterpreted as signed without checking for overflow.
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.
float(x)¶Convert a number, array, or string to a
AbstractFloatdata type. For numeric data, the smallest suitableAbstractFloattype is used. Converts strings toFloat64.
significand(x)¶Extract the
significand(s)(a.k.a. mantissa), in binary representation, of a floating-point number or array. Ifxis a non-zero finite number, than the result will be a number of the same type on the interval \([1,2)\). Otherwisexis returned.julia>significand(15.2)/15.20.125julia>significand(15.2)*815.2
exponent(x) → Int¶Get the exponent of a normalized floating-point number.
complex(r[, i])¶Convert real numbers or arrays to complex.
idefaults to zero.
bswap(n)¶Byte-swap an integer
num2hex(f)¶Get a hexadecimal string of the binary representation of a floating point number
hex2num(str)¶Convert a hexadecimal string to the floating point number it represents
hex2bytes(s::ASCIIString)¶Convert an arbitrarily long hexadecimal string to its binary representation. Returns an
Array{UInt8,1}, i.e. an array of bytes.
bytes2hex(bin_arr::Array{UInt8, 1})¶Convert an array of bytes to its hexadecimal representation. All characters are in lower-case. Returns an
ASCIIString.
General Number Functions and Constants¶
one(x)¶Get the multiplicative identity element for the type of
x(xcan also specify the type itself). For matrices, returns an identity matrix of the appropriate size and type.
zero(x)¶Get the additive identity element for the type of
x(xcan also specify the type itself).
im¶The imaginary unit
catalan¶Catalan’s constant
Inf¶Positive infinity of type
Float64
Inf32¶Positive infinity of type
Float32
Inf16¶Positive infinity of type
Float16
NaN¶A not-a-number value of type
Float64
NaN32¶A not-a-number value of type
Float32
NaN16¶A not-a-number value of type
Float16
issubnormal(f) → Bool¶Test whether a floating point number is subnormal
isfinite(f) → Bool¶Test whether a number is finite
isinf(f) → Bool¶Test whether a number is infinite
isnan(f) → Bool¶Test whether a floating point number is not a number (NaN)
inf(f)¶Returns positive infinity of the floating point type
for of the same floating point type asf
nan(f)¶Returns NaN (not-a-number) of the floating point type
for of the same floating point type asf
nextfloat(f)¶Get the next floating point number in lexicographic order
prevfloat(f) → AbstractFloat¶Get the previous floating point number in lexicographic order
isinteger(x) → Bool¶Test whether
xor all its elements are numerically equal to some integer
isreal(x) → Bool¶Test whether
xor all its elements are numerically equal to some real number
Float32(x[, mode::RoundingMode])¶Create a Float32 from
x. Ifxis not exactly representable thenmodedetermines howxis rounded.julia>Float32(1/3,RoundDown)0.3333333f0julia>Float32(1/3,RoundUp)0.33333334f0
See
get_roundingfor available rounding modes.
Float64(x[, mode::RoundingMode])¶Create a Float64 from
x. Ifxis not exactly representable thenmodedetermines howxis rounded.julia>Float64(pi,RoundDown)3.141592653589793julia>Float64(pi,RoundUp)3.1415926535897936
See
get_roundingfor available rounding modes.
BigInt(x)¶Create an arbitrary precision integer.
xmay be anInt(or anything that can be converted to anInt). The usual mathematical operators are defined for this type, and results are promoted to aBigInt.Instances can be constructed from strings via
parse(), or using thebigstring literal.
BigFloat(x)¶Create an arbitrary precision floating point number.
xmay be anInteger, aFloat64or aBigInt. The usual mathematical operators are defined for this type, and results are promoted to aBigFloat.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 viaparse(), or using thebigstring literal.julia>BigFloat(2.1)2.100000000000000088817841970012523233890533447265625000000000000000000000000000julia>big"2.1"2.099999999999999999999999999999999999999999999999999999999999999999999999999986
get_rounding(T)¶Get the current floating point rounding mode for type
T, controlling the rounding of basic arithmetic functions (+(),-(),*(),/()andsqrt()) and type conversion.Valid modes are
RoundNearest,RoundToZero,RoundUp,RoundDown, andRoundFromZero(BigFloatonly).
set_rounding(T, mode)¶Set the rounding mode of floating point type
T, controlling the rounding of basic arithmetic functions (+(),-(),*(),/()andsqrt()) and type conversion.Note that this may affect other types, for instance changing the rounding mode of
Float64will change the rounding mode ofFloat32. Seeget_roundingfor available modes
with_rounding(f::Function, T, mode)¶Change the rounding mode of floating point type
Tfor the duration off. It is logically equivalent to:old=get_rounding(T)set_rounding(T,mode)f()set_rounding(T,old)
See
get_roundingfor available rounding modes.
get_zero_subnormals() → Bool¶Returns
falseif operations on subnormal floating-point values (“denormals”) obey rules for IEEE arithmetic, andtrueif they might be converted to zeros.
set_zero_subnormals(yes::Bool) → Bool¶If
yesisfalse, 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. Returnstrueunlessyes==truebut 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¶
count_ones(x::Integer) → Integer¶Number of ones in the binary representation of
x.julia>count_ones(7)3
count_zeros(x::Integer) → Integer¶Number of zeros in the binary representation of
x.julia>count_zeros(Int32(2^16-1))16
leading_zeros(x::Integer) → Integer¶Number of zeros leading the binary representation of
x.julia>leading_zeros(Int32(1))31
leading_ones(x::Integer) → Integer¶Number of ones leading the binary representation of
x.julia>leading_ones(UInt32(2^32-2))31
trailing_zeros(x::Integer) → Integer¶Number of zeros trailing the binary representation of
x.julia>trailing_zeros(2)1
trailing_ones(x::Integer) → Integer¶Number of ones trailing the binary representation of
x.julia>trailing_ones(3)2
isprime(x::Integer) → Bool¶Returns
trueifxis prime, andfalseotherwise.julia>isprime(3)true
isprime(x::BigInt[, reps = 25]) → BoolProbabilistic primality test. Returns
trueifxis prime; andfalseifxis not prime with high probability. The false positive rate is about0.25^reps.reps=25is considered safe for cryptographic applications (Knuth, Seminumerical Algorithms).julia>isprime(big(3))true
primes([lo, ]hi)¶Returns a collection of the prime numbers (from
lo, if specified) up tohi.
primesmask([lo, ]hi)¶Returns a prime sieve, as a
BitArray, of the positive integers (fromlo, if specified) up tohi. Useful when working with either primes or composite numbers.
isodd(x::Integer) → Bool¶Returns
trueifxis odd (that is, not divisible by 2), andfalseotherwise.julia>isodd(9)truejulia>isodd(10)false
iseven(x::Integer) → Bool¶Returns
trueisxis even (that is, divisible by 2), andfalseotherwise.julia>iseven(9)falsejulia>iseven(10)true
BigFloats¶
The BigFloat type implements arbitrary-precision floating-point arithmetic using the GNU MPFR library.
precision(num::AbstractFloat)¶Get the precision of a floating point number, as defined by the effective number of bits in the mantissa.
get_bigfloat_precision()¶Get the precision (in bits) currently used for
BigFloatarithmetic.
set_bigfloat_precision(x::Int64)¶Set the precision (in bits) to be used to
BigFloatarithmetic.
with_bigfloat_precision(f::Function, precision::Integer)¶Change the
BigFloatarithmetic precision (in bits) for the duration off. It is logically equivalent to:old=get_bigfloat_precision()set_bigfloat_precision(precision)f()set_bigfloat_precision(old)
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))).
srand([rng][, seed])¶Reseed the random number generator. If a
seedis provided, the RNG will give a reproducible sequence of numbers, otherwise Julia will get entropy from the system. ForMersenneTwister, theseedmay be a non-negative integer, a vector ofUInt32integers or a filename, in which case the seed is read from a file.RandomDevicedoes not support seeding.
MersenneTwister([seed])¶Create a
MersenneTwisterRNG object. Different RNG objects can have their own seeds, which may be useful for generating different streams of random numbers.
RandomDevice()¶Create a
RandomDeviceRNG object. Two such objects will always generate different streams of random numbers.
rand([rng][, S][, dims...])¶Pick a random element or array of random elements from the set of values specified by
S;Scan be- an indexable collection (for example
1:nor['x','y','z']), or - a 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;
Sdefaults toFloat64.- an indexable collection (for example
rand!([rng, ]A[, coll])¶Populate the array
Awith random values. If the indexable collectioncollis specified, the values are picked randomly fromcoll. This is equivalent tocopy!(A,rand(rng,coll,size(A)))orcopy!(A,rand(rng,eltype(A),size(A)))but without allocating a new array.
bitrand([rng][, dims...])¶Generate a
BitArrayof random boolean values.
randn([rng][, dims...])¶Generate a normally-distributed random number with mean 0 and standard deviation 1. Optionally generate an array of normally-distributed random numbers.
randn!([rng, ]A::Array{Float64, N})¶Fill the array
Awith normally-distributed (mean 0, standard deviation 1) random numbers. Also see the rand function.
randexp([rng][, dims...])¶Generate a random number according to the exponential distribution with scale 1. Optionally generate an array of such random numbers.
randexp!([rng, ]A::Array{Float64, N})¶Fill the array
Awith random numbers following the exponential distribution (with scale 1).
randjump(r::MersenneTwister, jumps[, jumppoly]) → Vector{MersenneTwister}¶Create an array of the size
jumpsof initializedMersenneTwisterRNG objects where the first RNG object given as a parameter and followingMersenneTwisterRNGs in the array 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 polynomialjumppoly.Default jump polynomial moves forward
MersenneTwisterRNG state by 10^20 steps.