Using rustymath from Rust
Add rustymath to your Cargo.toml:
[dependencies]
rustymath = "0.1"On x86-64, build for a recent CPU, with -C target-cpu=x86-64-v3 or -C target-cpu=native. You can set it once in .cargo/config.toml:
[target.'cfg(target_arch = "x86_64")']
rustflags = ["-C", "target-cpu=x86-64-v3"]Rust’s default x86-64 target has no fused multiply-add and no vector instruction for floor or trunc. Without the setting, rustymath multiplies and adds separately. Some of its loops also run one item at a time.
Free functions such as exp are generic over f32, f64 and half::f16. The compiler inlines such a function into the loop that calls it, and vectorizes that loop:
use half::f16;
use rustymath::exp;
let e64 = exp(1.0f64); // 2.718281828459045
let e32 = exp(1.0f32); // 2.718282
let e16 = exp(f16::from_f32(1.0)); // 2.719For whole arrays, resolve a formula object such as Pow to an operation::Kernel. Kernel::map reads each argument through a ReadPlan and replaces the contents of an output Buffer. Here map reads x in order through ReadPlan::input, and repeats the exponent’s one item through ReadPlan::copy:
use rustymath::{
Pow, agreement::{Binding, Mapping, Missing, Read, ReadPlan}, buffer::{Buffer, Element},
domain::Variant, operation::{Kernel, Settings}, tolerant::Tolerance,
};
let x = [1.5, 2.0, 3.0];
let exponent = [2.0];
let sources = [Binding::full(f64::view(&x)), Binding::full(f64::view(&exponent))];
let plans = [ReadPlan::input(0, 3), ReadPlan::copy(1, 1, Mapping::Single, 3, Missing::Default)];
let reads = plans.each_ref().map(|plan| Read { sources: &sources, plan });
let pow = Kernel::resolve(Pow, Variant::checked(f64::DTYPE), [f64::DTYPE; 2]).unwrap();
let settings = Settings { tolerance: Tolerance::EXACT };
let mut squares = Buffer::with_capacity(pow.result_dtype(), 3);
pow.map(&reads, 0..3, settings, &mut squares).unwrap();
assert_eq!(f64::vec(squares).unwrap(), [2.25, 4.0, 9.0]);facts::Formula defines each formula object’s numerical rules, supported kinds, validity, ranges and derivatives. Kernel::resolve selects the kernel’s computing and result dtypes. Kernel::of selects a formula from a runtime facts::Op. Kernels use native bulk routines where a formula supplies them, and otherwise run its item formula. Their map, fold_read, fold_pieces and scan methods take shared agreement::Read plans. The kernel methods real, integers, complex and exact evaluate scalar arguments with the kernel’s numerical policy and return a Result.
use rustymath::{Exp, domain::Variant, operation::Kernel, buffer::{DType, FloatWidth, Width}};
let double = DType::Float(FloatWidth::F64);
let exp = Kernel::resolve(Exp, Variant::checked(double), [DType::Integer(Width::I32)]).unwrap();
assert_eq!(exp.variant().dtype, double);Sin, Cos and Tan use a short argument reduction and polynomials for arguments up to 2^23 at f64, or 2^20 at f32. An object’s repair predicate marks arguments of larger magnitude. Its native slice driver applies the object’s scalar repair routine to those items before returning the results. Kernel::ranged omits repair when the same predicate is proved false over the supplied ranges.
atan2(y, x) and a kernel of Atan2 give the angle of the point (x, y), from -π to π. y comes first, as in f64::atan2.
divide(x, y) divides complex numbers and is inlined into the caller’s loop, like the other free functions. When both arguments are real, divide divides them as reals: a real zero divisor gives ±∞ or NaN, with an imaginary part of 0. The |y|² in its formula overflows when |y| is beyond about 1e154 at f64 and 1e19 at f32.
Tolerant comparison
The tolerant module has APL’s tolerant comparison: x equals y when |x - y| is less than the tolerance times the larger of |x| and |y|. Its formula objects, such as Equal, Less, Floor, Residue and Gcd, hold a Tolerance. operation::Settings supplies the tolerance for a kernel execution. With Tolerance::EXACT, a kernel chooses ordinary comparison once for the whole call. A comparison kernel produces Boolean array results; its scalar real method represents true and false as 1 and 0:
use rustymath::{
buffer::Element, domain::Variant, operation::{Kernel, Settings}, tolerant::{Equal, Tolerance},
};
let equal = Kernel::resolve(Equal(Tolerance::DEFAULT), Variant::checked(f64::DTYPE), [f64::DTYPE; 2]).unwrap();
let settings = Settings { tolerance: Tolerance::DEFAULT };
let same = [0.3, 0.1 + 0.2, 0.31].map(|x| equal.real(&[x, 0.3], settings).unwrap());
assert_eq!(same, [1.0, 1.0, 0.0]);Other modules
number_theory: primality, factorisation, next and previous primes, Euler’s totient, and the enumeration and counting of primes, on au64, au128or aBigUint. Each function computes in the narrowest of those types that holds the value. A function that can run for a long time checks for an interrupt between steps.factorialgives n! as aBigUint.optimize:minimizefinds the minimum of a function of anf32orf64slice. It uses Brent’s method for one variable, Nelder–Mead, Powell’s conjugate directions, L-BFGS with a gradient, or differential evolution within bounds.solvefinds a zero or a least-squares solution of a function that returns a slice. It uses Brent’s method for one equation in one variable and Levenberg–Marquardt otherwise.solve_linearsolves a linear system or finds its least-squares solution using only products of the matrix with vectors. It uses conjugate gradients, MINRES or restarted GMRES, with an optional preconditioner.solve_affineuses the same methods to solve f(x) = 0 for an affine function, using only the function’s values.Method::choosepicks a method when the caller does not specify one. Functions implementObjectiveorMapping. They can be closures that return aResult, whose error stops the search, or types that also provide a gradient, vector–Jacobian products or batches of points.polynomial: evaluation over a slice by Horner’s rule, roots from the eigenvalues of the companion matrix, building from roots, derivatives and least-squares fitting. Roots are sorted by real part, then imaginary part.valueandfactoredevaluate at one point.value,factored,from_rootsandderivativetake any type with the field operations, such as exact rationals. So dodecode, which gives the values of digits in a mixed radix, andencode, which gives the digits of values.reduce: sums, products, maximums and minimums over a slice, and their running versions.Reduction, implemented bySum,Product,MaxandMin, defines each reduction’s unit, step for one more item, fold of a slice, merge of the folds of two neighbouring runs, and scan. Itscheckedmethod takes one step and reports whether the result fits. Float sums and products vectorize by combining the items in any order. Integer sums and products, running ones included, wrap where they don’t fit and report whether they fit.extremesgives the least and the greatest item in one pass.Alternated<Sum>andAlternated<Product>are the right folds by-and÷, written as reductions so that every function that folds by aReductionaccepts them. The right fold by-gives the sum of the items at even positions less the sum of those at odd positions. The right fold by÷gives the product of the items at even positions divided by the product of those at odd positions. Each total records whether its count of items is even or odd.Totalsdrops that record when it stores the totals in a buffer. For floats,Alternated<Product>reports that the result doesn’t fit when a running quotient leaves the normal range. Booleans fold byMaxasor, byMinasand, byXoras not-equal, byXnoras equal, and bySumAsas a count of trues.Logicalscans Booleans by any function of two Booleans, given as its truth table.SumAs<C>also sums integers through the traitsTermandTally. The sum wraps in the typeC, which the caller picks to hold every sum: a byte,i16,i32ori64.alongandscan_alongfold and scan along the middle axis of a row-major array of shape[outer, len, inner]. For example,[1, rows, columns]folds or scans down the columns of a matrix.fold_intofolds the same array one block at a time, for a caller that computes the array in blocks. Each row length under 16, such as an image’s 3 channels, has its own loop. A running maximum or minimum of integers writes its current value across each block of 256 items that doesn’t change it.along_mappedfolds an array defined by a mapping over storage, without building the array.slidingfolds each window of neighbouring rows.picksandview_picksgive, for each window, lane or running fold, the row of the first item that attains its maximum or minimum.linalg: inner products of row-major matrices through theInnertrait. These include the matrix productPlusTimes, which also takes complex matrices; the max-plus and min-plus productsMaxPlusandMinPlus; the counts of equal and unequal itemsPlusEqualandPlusNotEqual; and the Boolean productsOrAndandAndOr. Each numeric pair also takesi64matrices, whose arithmetic wraps.Inner::checked_intogivesfalsewhere an integer result doesn’t fit.Productselects an inner-product pair at run time.Product::runcomputes its products through the kernel for the arguments’ dtype. The inner-product routines process matrices in blocks sized for the caches, as GotoBLAS and BLIS do. Their innermost loops use explicit vector instructions on AArch64, in wasm and on x86-64 with AVX2.linalg’s decompositions of real and complex matrices arelu,cholesky,qr,qr_completeandsvd, atf32,f64andComplexwith parts of either type. It also hasLu::solve,Lu::inverse,Lu::lower,Lu::upper,Lu::determinant,Lu::log_determinant,Svd::solve,Svd::pseudoinverse,singular_valuesand the least-squares solverlstsq.solveandpinvgive the least-norm solution and the pseudoinverse of any matrix, singular or not.rankcounts the singular values abovelstsq’s cutoff.eighandhermitian_eigenvaluestake Hermitian matrices, andis_hermitiantests whether a matrix is Hermitian.eigandeigenvaluestake any square matrix.from_svd,from_cholesky,from_eigenandfrom_lumultiply a decomposition’s factors back into its matrix.transpose_intotransposes a matrix through 8×8 tiles, applying a conversion to each item.Scalaris the sealed trait implemented by the four matrix item types.linalg::exactworks in any field, such as exact rationals:echelon,solve,pinv,determinantand Ryser’spermanent.exact:residue,gcd,lcmandbinomof exact rationals over any integer type, such asBigRational.distribution: sixteen distributions. The objectsPdf,CdfandQuantilehold a distribution and evaluate it over a slice. Each distribution also samples from a seeded generator.array:Array, aLayoutpaired with theBufferthat holds one item for each of its positions, in row-major order.create: filled arrays and integer or floating ranges, evenly spaced values and logarithmically spaced values.stats: means, two-pass variance and standard deviation, weighted averages, elementwise p-norms, covariance, correlation and histograms.Axesprepares reductions over selected axes. Complex variance and norms return real values.search: exact search and classification, stable counting/radix sorting, partitioning and quantiles.selectmoves the items of the requested ranks to their sorted positions without sorting the items between them. Its functions that take aViewsupport the same dtypes as BasedPL and the Python package. Ordering compares floats exactly, treats signed zeros as equal and puts NaNs last in ascending order.buffer: compact buffers.Bufferholds items of one element type, andViewborrows them.DTypenames the type: Booleans, integers of four widths (Width), floats of three (FloatWidth), complex numbers of two (ComplexWidth), or characters.DType::commongives the dtype that NumPy promotes two dtypes to, andDType::inexactthe dtype that a function of floats computes in.IntBuf,FloatBufandComplexBufeach hold items of one family, at any of its widths. Their views areInts,FloatsandComplexes. The macroswith_ints!,with_floats!andwith_complexes!run code on a view’s slice.with_width!,with_float_width!andwith_complex_width!run code on a width’s element type.with_dtype!runs code on aDType’s element type.Elementdefines each element type’s fill. Itsof,viewandbuffermethods convert between slices of that type and aViewor aBuffer.Sourcereads an item of one type as another.error: array functions returnError, which contains a message and aKind: Length, Rank, Index, Limit, Domain, Overflow, Interrupt or Timeout.interrupt: the process’s interrupt check. A frontend installs one withinstall. Long computations callcheckbetween steps, about everyBETWEEN_CHECKSitems, and stop if it returns an Interrupt or Timeout error. Until a frontend installs a check,checkalways succeeds.memory: the process’s memory guard. When a binary registersGuardas its global allocator, Rust aborts the process if an allocation would take the total size of its large allocations past the process’s limit. The limit defaults to half of physical memory and can be changed withset_limit. Before an allocation,layout::generated_lencallsadmit, which returns a Limit error if the array would pass the limit.layout: array shapes, axis keys and names, and their limits.Shapeholds an array’s axis lengths.Keysnames the positions on one axis.Layoutpairs a shape with keys and a name for each axis.Layout::axis_namedfinds an axis by its name.positionconverts an index to a position within an axis of a given length, counting from the end when the index is negative.Lanesdescribes an array’s items as lanes along one axis. It provides each item’soffsetand thedimsthat rustymath’s axis functions take.element_countandgenerated_lencount an array’s items and enforce the limits ofMAX_RANKaxes andMAX_GENERATED_ELEMENTSitems.generated_lenalso enforces the memory guard’s limit.stridesgives the distance between neighbouring items along each axis.agreement: broadcasting by BasedPL’s rule.Agreement::newpairs the axes of two layouts: axes with the same name first, then the rest from the front. If every axis of the left layout pairs and the right layout has more axes, the result uses the right layout’s axis order. Otherwise, the left layout’s axes come first. An axis of length 1 repeats along its partner. If both layouts have keys for an axis, the result uses the union of those keys. The result is the paired layout and aMappingfor each argument, which gives the argument’s offset for each result position.blocksruns a kernel over two slices using an agreement, passing contiguous runs whole.expandedreads one argument’s items for a range of result positions.Agreementis generic over its layout type, so callers can usemap_layoutto carry their own data on layouts.Framespairs the frames of any number of arguments to a function that operates on their trailing axes, such as matrices in a stack. For each result cell, it gives the corresponding cell of each argument.random: uniform floats, bounded integers and sampling without replacement.roll,units,belowanddealdraw through a caller’s mutablerand::Rng.gather: copying a slice’s items into a buffer by position. It providescycle,repeat,positionsset in a mask,takeat indices,windows,walkalong a pattern ofStepswith fills, andscatterat offsets. Each applies the caller’s conversion to each item.walkalso takesSame, which copies whole slices of one type.Steps::reachgives the source offset of one item of a walk.Steps::rungives the source offset of a run of items that lie in order in the source.Steps::throughcomposes two walks into one.Steps::per_axisgives a walk one entry for each axis of its result.Steps::spreadstells whether an entry repeats an offset or gives a fill, andSteps::rereadswhether two entries walk one source axis, as overlapping windows do.structure: plans for structural operations. APlanholds the result’sLayoutand theStepsthatwalkfollows to copy the result’s items from the source.selectapplies independent axis selectors for positions, ranges, index arrays and inserted axes. Index arrays are paired in one of two ways: all of them by broadcasting, as BasedPL’s.[]reads them, or only those that share an axis name, as BasedPL’s⌷reads them.addressedgives the axis that each selector selects along.taketakes or drops items.rotaterotates or reverses an axis, using one count or one count for each lane.transposesends axes to new positions.catenategives the layout of two arrays joined along an axis.Windowsplans windows over leading axes, centred on each position of a padded axis. AnEdgemode sets how the plan reads past the axis’s ends.Walkdescribes how a copy walks its source, giving the source axis that each entry walks. For the entries along one source axis,readandrangegive what they read as windows: where the windows start, and each entry’s length and move.Walk::windowsrecognises a copy of windows laid out byWindows::planwithout padding. It gives each axis’s frames, window size and move.Transposegives the kernel that adds a copy’s cotangent back to its source: a sum along its spread axes, then reads that send each item back, overlap-add for windows that move by more than 1, or a scatter-add. Each plan checks its arguments. In each plan’s result, axis keys and names stay with their positions.signal: correlations and convolutions, which slide a kernel along an array’s leading axes, and overlap-add.correlationgives the plans used to read a correlation: the array with the fills added by itsMode, the array’s windows, and the kernel. For a convolution, the kernel is reversed.correlateruns these plans through anInnerpair’sinner_mapped. Float and complexPlusTimesread the windows a block at a time.overlap_addadds each frame back where its window was read. This is the transpose of taking windows.convert:intconverts a whole float to an integer type. It givesNoneoutside the type’s range, and fori64beyond a magnitude of 2^51 - 1.floatconverts an integer to the nearest float. Loops that call either vectorize on every target. AVX2 and wasm lack a vector instruction for conversion betweenf64and 64-bit integers. On those targets a loop that converts withasruns one item at a time.
Like elementary functions, the special functions have free functions and objects at the crate root. These include gamma, lgamma, digamma, erf, erfc, their inverses, binom with its slopes binom_dn and binom_dk, the incomplete gamma and beta functions and Lambert W.
Add, Subtract, Multiply and the other arithmetic objects at the crate root implement Formula. Kernel runs these arithmetic objects at every float, complex and integer type, using the checking and wrapping policy specified by its Variant. For unbounded rationals, call Kernel::exact, which delegates to Formula::exact.
Accuracy and speed
The table gives nanoseconds per item for each function and for the standard library’s version of it, measured with a loop over 65,536 inputs on an Apple M5 Max in October 2026. A row named after an object gives the time of its bulk kernel. The rows Pow.one and Root.one give the time of the scalar formulas, called on one pair of arguments at a time. To print the table on your own machine, run RUSTYMATH_COSTS=1 cargo test --test speed.
| Function | f64 | std f64 | f32 | std f32 |
|---|---|---|---|---|
Exp |
0.68 | 3.92 | 0.26 | 0.91 |
Expm1 |
0.75 | 2.70 | 0.30 | 3.10 |
Ln |
0.84 | 1.62 | 0.40 | 1.39 |
Log1p |
1.37 | 2.31 | 0.67 | 1.39 |
Log2 |
0.80 | 1.62 | 0.41 | 1.27 |
Log10 |
0.85 | 1.74 | 0.40 | 1.27 |
Sin |
0.87 | 4.95 | 0.36 | 4.68 |
Cos |
0.91 | 5.12 | 0.40 | 5.01 |
Tan |
1.14 | 2.58 | 0.45 | 4.68 |
Asin |
0.94 | 4.55 | 0.34 | 3.83 |
Acos |
1.03 | 6.03 | 0.37 | 5.15 |
Atan |
0.89 | 6.04 | 0.34 | 2.16 |
Sinh |
1.26 | 2.47 | 0.56 | 2.37 |
Cosh |
0.95 | 2.27 | 0.38 | 2.30 |
Tanh |
0.94 | 3.44 | 0.37 | 2.28 |
Asinh |
1.50 | 2.56 | 0.69 | 1.87 |
Acosh |
1.59 | 2.17 | 0.68 | 1.56 |
Atanh |
1.40 | 3.78 | 0.62 | 1.62 |
Cbrt |
1.11 | 1.39 | 0.89 | 1.85 |
Pow |
2.92 | 7.28 | 1.61 | 2.06 |
Pow.one |
4.11 | 7.18 | 2.27 | 1.97 |
Hypot |
0.55 | 1.21 | 0.27 | 0.87 |
Root |
3.38 | 4.24 | 1.76 | 1.96 |
Root.one |
4.23 | 4.25 | 2.36 | 2.09 |
Maximum |
0.19 | 0.19 | 0.10 | 0.09 |
reduce::sum |
0.06 | 0.49 | 0.03 | 0.46 |
reduce::max |
0.06 | 0.11 | 0.03 | 0.05 |
reduce::Sum::scan |
0.15 | 1.94 | 0.15 | 2.61 |
reduce::Max::scan |
0.15 | 2.53 | 0.07 | 2.54 |
polynomial::evaluate |
0.51 | 2.60 | 0.22 | 2.60 |
Functions on f16 compute in f32 and round once. IEEE 754 conformance for infinities, NaNs and signed zeros is not promised. The tests compare finite results with references at every f16 input, at samples of f32 and f64 inputs, and at published hard cases.
Where the target has a fused multiply-add instruction, as on AArch64 and on x86-64 with FMA, the functions use it. Elsewhere, as in wasm, they multiply and add separately, because calling a software fma would prevent the compiler from vectorizing the loop. The constant FUSED is true where the target uses fused multiply-add. The modules fused and unfused contain every function again, with fused multiply-add always on or always off. In a loop compiled with FMA for itself, such as an AVX2 version that your program chooses at run time, call fused. Either way, results stay within 4 ulps of the correctly rounded result, apart from the documented exceptions.
General powers and roots use compensated native block algorithms. At f64, logarithms and exponentials use tables. Exceptional inputs take the scalar repair path. Cheap constant powers, square roots and cube roots use specialized formulas.