Expand description
zenith-float implements arbitrary-precision software floating-point numbers
(ExactNum) and software IEEE-754 binary32/binary64 (Ieee32 / Ieee64).
All arithmetic uses integer limbs. The library does not use hardware floating-point for calculations.
Repository guides: doc/GETTING_STARTED.md (short path) and doc/HELP.md (longer tutorial).
Inventory: doc/ZENITH_FLOAT_CAPABILITIES.md. Patches: CONTRIBUTING.md.
§Introduction
Numbers
The number is defined by the data type ExactNum.
Each finite number consists of an array of words representing the mantissa, exponent, and sign.
ExactNum can also be Inf (positive infinity), -Inf (negative infinity) or NaN (not-a-number).
ExactNum creation operations take bit precision as an argument.
Precision is always rounded up to the nearest word.
For example, if you specify a precision of 1 bit, then it will be converted to 64 bits when one word has a size of 64 bits.
If you specify a precision of 65 bits, the resulting precision will be 128 bits (2 words), and so on.
Most operations take the rounding mode as an argument. The operation will typically internally result in a number with more precision than necessary. Before the result is returned to the user, the result is rounded according to the rounding mode and reduced to the expected precision.
The result of an operation is marked as inexact if some of the bits were rounded when producing the result, or if any of the operation’s arguments were marked as inexact. The information about exactness is used to achieve correct rounding.
ExactNum can be parsed from a string and formatted into a string using binary, octal, decimal, or hexadecimal representation.
Numbers can be subnormal. Usually any number is normalized: the most significant bit of the mantissa is set to 1. If the result of the operation has the smallest possible exponent, then normalization cannot be performed, and some significant bits of the mantissa may become 0. This allows for a more gradual transition to zero.
Error handling
In case of an error, such as memory allocation error, ExactNum takes the value NaN.
ExactNum::err() can be used to get the associated error in this situation.
Constants
Constants such as pi or the Euler number have arbitrary precision and are evaluated lazily and then cached in the constants cache. Some functions expect constants cache as parameter.
Rounding
ExactNum methods that take a rounding mode other than RoundingMode::None round to the requested precision.
RoundingMode::None skips that step and may keep extra bits.
expr! raises working precision to compensate cancellation; it does not itself perform correct rounding.
§Examples
The example below computes Pi with precision 1024, rounding to even, using expr!.
use zenith_float::Consts;
use zenith_float::RoundingMode;
use zenith_float::ctx::Context;
use zenith_float::expr;
// Create a context with precision 1024, rounding to the nearest even,
// and exponent range from -100000 to 100000.
let mut ctx = Context::new(1024, RoundingMode::ToEven,
Consts::new().expect("Constants cache initialized"),
-100000, 100000);
// Compute pi: pi = 6*arctan(1/sqrt(3))
let pi = expr!(6 * atan(1 / sqrt(3)), &mut ctx);
// Use library's constant value for verifying the result.
let pi_lib = ctx.const_pi();
// Compare computed constant with library's constant
assert_eq!(pi.cmp(&pi_lib), Some(0));
// Print using decimal radix.
#[cfg(feature="std")]
println!("{}", pi);
// output: 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196442881097566593344612847564823378678316527120190914564856692346034861045432664821339360726024914127372458699748e+0The example below computes value of Pi with precision 1024 rounded to the nearest even number using ExactNum directly.
We will take care of the error in this case.
use zenith_float::ExactNum;
use zenith_float::Consts;
use zenith_float::RoundingMode;
// Precision with some space for error.
let p = 1024 + 8;
// The results of computations will not be rounded.
// That will be more performant, even though it may give an incorrectly rounded result.
let rm = RoundingMode::None;
// Initialize mathematical constants cache
let mut cc = Consts::new().expect("An error occured when initializing constants");
// Compute pi: pi = 6*arctan(1/sqrt(3))
let six = ExactNum::from_word(6, 1);
let three = ExactNum::from_word(3, p);
let n = three.sqrt(p, rm);
let n = n.reciprocal(p, rm);
let n = n.atan(p, rm, &mut cc);
let mut pi = six.mul(&n, p, rm);
// Reduce precision to 1024 and round to the nearest even number.
pi.set_precision(1024, RoundingMode::ToEven).expect("Precision updated");
// Use library's constant for verifying the result
let pi_lib = cc.pi(1024, RoundingMode::ToEven);
// Compare computed constant with library's constant
assert_eq!(pi.cmp(&pi_lib), Some(0));
// Print using decimal radix.
#[cfg(feature="std")]
println!("{}", pi);
// output: 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196442881097566593344612847564823378678316527120190914564856692346034861045432664821339360726024914127372458699748e+0§Performance recommendations
When small error is acceptable because of rounding it is recommended to do all computations with RoundingMode::None, and use ExactNum::set_precision or ExactNum::round with a specific rounding mode just once for the final result.
§no_std
The library can work without the standard library provided there is a memory allocator. The standard library dependency is activated by the feature std.
The feature std is active by default and must be excluded when specifying dependency, e.g.:
[dependencies]
zenith-float = { version = "1.0.1", default-features = false }Modules§
- ctx
- Context is used in expressions returning
ExactNum.
Macros§
- cexpr
- Computes an expression with the specified precision and rounding mode.
- exact
- Computes an expression with the specified precision and rounding mode.
- expr
- Computes an expression with the specified precision and rounding mode.
- fbig
- Computes an expression with the specified precision and rounding mode.
Structs§
- Ball
- Enclosure
mid ± radused to certify that a rounded midpoint is unique. - CachedF
Big - A float stored at extra working precision so later requests at lower (or equal) precision reuse the cache instead of recomputing.
- Complex
Ball - Disk enclosure in (\mathbb{C}): center
mid, radiusrad. - Const
Cache Info - Snapshot of how many mantissa bits of each constant are currently cached.
- Consts
- Constants cache contains arbitrary-precision mathematical constants.
- Exact
Complex - Complex value
re + i·imwith software-limb real and imaginary parts. - Exact
Int - Arbitrary-precision signed integer. Distinct from
ExactNum, which is floating-point. - Exact
Num - A floating point number of arbitrary precision.
- Exact
NumArray - Batch of
ExactNumvalues at a shared precisionp, row-major. - Exact
NumPoly - Dense univariate polynomial
c₀ + c₁ x + ⋯ + cₙ xⁿ. - Exact
Rational - Exact rational
num/den. Distinct fromExactNum, which is floating-point. - Ieee32
- Software IEEE-754 binary32 (24-bit significand, 8-bit exponent). Stored as
u32bits. - Ieee64
- Software IEEE-754 binary64 (53-bit significand, 11-bit exponent). Stored as
u64bits. - Ieee32
Array - Contiguous binary32 lanes (
u32bits), row-major. - Ieee64
Array - Contiguous binary64 lanes (
u64bits), row-major. - Inline
Binary Buffer - Fixed 16-byte stack buffer for an inlined
ExactNum. - Radix
- Radix for parse/format (bases 2 through 36).
- Radix
Float - A floating-point value with an associated parse/format radix.
- Shared
Consts - Thread-safe
Constsfor batch evaluation across threads (stdonly). Callers still take&mut ConstsinsideSharedConsts::with; the mutex serializes cache fills.
Enums§
- Error
- Possible errors.
- Rounding
Mode - Rounding modes.
- Sign
- Sign.
Constants§
- BINARY_
FLAG_ ARRAY ExactNumArrayrecord.- BINARY_
FLAG_ HEAP_ NEG - Heap finite, negative.
- BINARY_
FLAG_ HEAP_ POS - Heap finite, positive.
- BINARY_
FLAG_ INF_ NEG INF_NEG.- BINARY_
FLAG_ INF_ POS INF_POS.- BINARY_
FLAG_ NAN_ BARE - NaN with no associated
Error. - BINARY_
FLAG_ NAN_ DIV0 - NaN:
Error::DivisionByZero. - BINARY_
FORMAT_ VERSION - First-byte version stored in every record.
- BINARY_
HEADER_ LEN - Header bytes of a heap or array record (same size as the inline record).
- BINARY_
INLINE_ LEN - Bytes in
InlineBinaryBuffer/ExactNum::to_inline_bytes. - BINARY_
INLINE_ MANT_ BITS - Mantissa bits that fit in the inline record (
2 × 32). - BINARY_
INLINE_ U32_ WORDS u32limbs in the inline mantissa field.- BINARY_
MAX_ ELEMS - Maximum array elements accepted by
ExactNumArray::from_bytes. - BINARY_
MAX_ U32 - Maximum
u32limbs accepted byExactNum::from_bytes. - CHEBYSHEV_
MAX_ DEGREE - Maximum number of Chebyshev coefficients
chebyshev_coeffswill compute. - CSV_
MAX_ COLS - Maximum columns accepted in one CSV row.
- CSV_
MAX_ ROWS - Maximum data rows accepted by
Ieee64Array::from_csv_str. - DSP_
MAX_ POINTS - Maximum real length for
dct/idct/dst/idstand the window generators. Transforms use a2N-point FFT, so this is half ofFFT_MAX_POINTS. - EXPONENT_
BIT_ SIZE - The size of exponent type in bits.
- EXPONENT_
MAX - Maximum exponent value.
- EXPONENT_
MIN - Minimum exponent value.
- IEEE_
SIMD_ LANE_ WIDTH - Number of
u32lanes in one integer SIMD vector (128-bit register). Binary64 usesIEEE_SIMD_LANE_WIDTH / 2u64lanes. Scalar fallback uses the same width so wrappers can size buffers withoutcfg. - INF_NEG
- Negative infinity.
- INF_POS
- Positive infinity.
- INLINE_
WORDS - Number of words kept on the stack before allocating.
- JACOBI_
AGM_ MAX - AGM / descending Landen steps for
am,sn,cn,dn. - MAX_
PREC_ RETRY - Maximum extra correct-rounding retries.
- NAN
- Not a number.
- ODE_
MAX_ STEPS - Maximum accepted steps for any solver in this module.
- ODE_
MIN_ STEP - Default minimum step exponent:
h_min = 2^{ODE_MIN_STEP}. - ORTHOPOLY_
N_ MAX - Maximum degree for every family in this module. Larger
nisNaN. - POLLARD_
RHO_ ITER_ MAX - Maximum
fevaluations in onepollard_rhorun beforeNone. - POLY_
COMPANION_ CLOSED_ DEG - Highest degree whose companion eigenvalues have a closed form on this type.
- PROPTEST_
CASES - Cases per
proptestproperty undercargo test(nompfr-testsrequired). - QUADRATURE_
MAX_ NODES - Maximum number of Gauss nodes. Larger
nisNone. - ROOT_
DEFAULT_ TOL - Default absolute tolerance exponent:
tol = 2^{ROOT_DEFAULT_TOL}. - ROOT_
MAX_ ITER - Maximum iterations for every method in this module.
- TANH_
SINH_ LEVELS_ MAX - Maximum tanh–sinh step halvings after the precision-based
h. - WORD_
BASE - Base of words.
- WORD_
BIT_ SIZE - Size of a word in bits.
- WORD_
MAX - Maximum value of a word.
- WORD_
SIGNIFICANT_ BIT - Word with the most significant bit set.
Traits§
- FromExt
- A trait for conversion with additional arguments.
Functions§
- bisect
- Bisection on
[a, b].Noneiff(a)andf(b)do not have opposite signs. - blackman_
window - Symmetric Blackman:
0.42 − 0.5 cos(θ) + 0.08 cos(2θ),θ = 2πk/(n−1). - brent
- Brent’s method (bisection + secant + inverse quadratic) on
[a, b]. - chebyshev_
coeffs - Interpolation coefficients of
fon[a, b]at thenChebyshev–Gauss nodes. - chebyshev_
error_ bound - ℓ¹ tail
Σ_{k≥1} |c_k|at precisionp. - chebyshev_
eval - Evaluate the Chebyshev expansion of
coeffsatx ∈ [a, b]. - clenshaw
- Clenshaw recurrence for
Σ_{k=0}^{n-1} c_k T_k(x)at precisionp. - constant_
time_ eq - Timing-safe equality: always scans both slices; length mismatch is
false. - dct
- Discrete cosine transform, type II, via a
2N-point FFT. - dst
- Discrete sine transform, type II, via a
2N-point FFT. - euler
- Explicit Euler for
y' = f(t, y)on[t0, t1]withn_stepsequal steps. - fft_
real - Unnormalized DFT of a real row or column. Output is
(2, n)(row 0 real, row 1 imaginary). Same power-of-two rule asExactNumArray::fft. - gauss_
hermite - Gauss–Hermite quadrature:
∫_{-∞}^{∞} f(x) e^{-x²} dxwithnnodes. - gauss_
laguerre - Gauss–Laguerre quadrature:
∫₀^∞ f(x) e^{-x} dxwithnnodes. - gauss_
legendre - Gauss–Legendre quadrature of
fon[a, b]withnnodes. - hamming_
window - Symmetric Hamming:
0.54 − 0.46 cos(2πk/(n−1)). Endpoints are0.08. - hann_
window - Symmetric Hann:
½(1 − cos(2πk/(n−1))).n = 1is[1]. - hmac_
sha256 - HMAC-SHA-256 (
key,data). - idct
- Inverse of
dct: type-III DCT scaled by2/Nsoidct(dct(x)) = x. - idst
- Inverse of
dst: type-III DST scaled by2/Nsoidst(dst(x)) = x. - ifft_
real - Inverse of
fft_real:ExactNumArray::ifftthen the real row. - illinois
- Illinois (modified regula falsi) on
[a, b]. - kaiser_
window - Kaiser–Bessel:
I_0(β √(1−t_k²)) / I_0(β)witht_k = (k−(n−1)/2)/((n−1)/2). - miller_
rabin - Miller–Rabin on
|n|with the given bases.n < 2isfalse. - mod_inv
- Modular inverse of
amodulomodulus.Noneif not invertible. - mod_pow
base^exp mod modulus.exp < 0or a zero modulus isNone.|modulus| = 1is0.- newton
- Newton–Raphson from
x0with exact derivativedf. - ode_
min_ step - Minimum step
2^{ODE_MIN_STEP}at precisionp. - pollard_
rho - Brent Pollard ρ. A proper factor of
|n|, orNoneif prime / cap hit. - rectangular_
window - Rectangular window:
nones. - rk4
- Classical RK4 for
y' = f(t, y)on[t0, t1]withn_stepsequal steps. - rk45_
adaptive - Dormand–Prince RK5(4) with absolute / relative step control.
- root_
default_ tol - Suggested absolute tolerance
2^{ROOT_DEFAULT_TOL}at precisionp. - sha256
- SHA-256 of
data. - sha512
- SHA-512 of
data. - tanh_
sinh - Tanh–sinh (double-exponential) quadrature of
fon[a, b]. - ziv_
round - Evaluate
computeat increasing working precision until the result rounds uniquely topbits (try_set_precision). Same retry budget as the transcendental kernel (crate::MAX_PREC_RETRY). - ziv_
round_ vec - Same Ziv loop as
ziv_round, with every input lifted top_wrkbeforecompute.
Type Aliases§
- Const
Cache - Alias for
Consts: a progressive cache of π, e, ln 2, ln 10, √2, φ, and γ. - Exponent
- An exponent.
- Word
- A word.