Skip to content

Foundations: API index

Find an operation by its purpose. Entries link to the complete signature and contract.

HMath.API.Algebra

API Purpose
Ring Implement zero, one, additive inverse, addition, multiplication and integer embedding.
zero Additive identity of this ring.
one Additive identity of this ring.
plus Additive identity of this ring.
times Additive identity of this ring.
negative Additive identity of this ring.
integer Additive identity of this ring.
Field Ring supporting checked multiplicative inversion.
invert Return multiplicative inverse of a nonzero domain element, or Left MathError for zeroinvalidnonrepresentable inverse.
Scalar Ring with conjugation,used by Hermitian inner-product algorithms.
conjugateScalar Return scalar conjugate; real/exact instances use identity and complex instances conjugate imaginary components.
FloatingPoint Scalar domain exposing precision epsilon and finite-value classification,including complex component checks.
machineEpsilon Given a type proxy, return floating precision epsilon as Double (2^-52 for Double,2^-23 for Float).
finiteScalar Given a type proxy, return floating precision epsilon as Double (2^-52 for Double,2^-23 for Float).
Numeric A numeric domain's conversion from a rational may fail, for example when an exact ring cannot represent a non-integral value.
rational Convert exact Rational into the domain, returning Left MathError if it cannot be represented under the instance contract.
MatrixLike Container interface for matrix dimensions,row-major elements,and checked construction.
matrixDimensions Return logical (rows,columns) of a matrix-like container.
matrixElements Return logical (rows,columns) of a matrix-like container.
matrixConstruct Return logical (rows,columns) of a matrix-like container.
TensorLike Container interface for tensor dimensions,row-major logical elements,and checked construction.
tensorDimensions Return tensor-like dimensions in axis order; [] denotes scalar.
tensorElements Return tensor-like dimensions in axis order; [] denotes scalar.
tensorConstruct Return tensor-like dimensions in axis order; [] denotes scalar.
VectorSpace Container interface for checked shape-compatible addition and scalar multiplication.
vectorPlus Add identically shaped vector-space values, returning checked dimension errors on mismatch.
vectorScale Add identically shaped vector-space values, returning checked dimension errors on mismatch.
Differentiable Differential extraction reuses the existing nested forward-mode Dual type.
Differential Differential extraction reuses the existing nested forward-mode Dual type.
differential Extract associated differential; the Dual instance returns its tangent component.
horner Coefficients are highest degree first; an empty polynomial is zero.
innerProduct Return sum(conjugate a[i] * b[i]) using the Scalar and Ring operations.
Exact An example user-definable domain, exact rationals with the explicit algebra contracts.
Exact Declaration and type contract below.
getExact Extract the exact Rational stored in the example Exact algebra domain.

HMath.API.Buffer

API Purpose
Boxed Immutable boxed array preserving element laziness unless built with strictBoxed; conversions preserve logical order.
lazyBoxed Finite lists only.
strictBoxed Construct a boxed container from a finite list, forcing every element to weak head normal form (not deep normal form).
boxedValues Return boxed elements in zero-based array order as a list.
boxedLength Return the number of elements in a boxed container; empty storage has length zero.
mapStrict Given element transformation then boxed input, return a boxed result with every mapped element forced to WHNF.
UnboxedDouble Immutable unboxed Double storage.
unboxedDouble Copy a finite Double list into an immutable unboxed array in list order.
unboxedValues Copy/expand unboxed Doubles into a list in array order, preserving length.
STBuffer Mutable boxed storage confined by the ST state parameter.
runSTBuffer The rank-2 state parameter prevents a mutable region from escaping.
thawSTBuffer Copy immutable boxed values into new mutable storage in the current ST region.
freezeSTBuffer Copy current mutable ST values into an immutable boxed container; later writes do not modify the frozen result.
readSTBuffer Given ST buffer then zero-based index, read the element.
writeSTBuffer Given ST buffer, zero-based index, then value, update one element and return Right ().
IOBuffer Pinned garbage-collected Storable buffer with synchronized IO access.
newIOBuffer Allocation overflow is checked before allocation.
thawIOBuffer Copy boxed Storable values into new pinned IO storage.
freezeIOBuffer Lock and copy pinned IO values to a strict immutable boxed container.
ioBufferLength Return the immutable element count of a pinned IO buffer.
readIOBuffer Given IO buffer then zero-based index, read under the buffer lock.
writeIOBuffer Given IO buffer, zero-based index, then value, write under its lock and return Right ().
withIOBuffer Given IO buffer then callback, hold its lock and lend a Ptr plus element count for the callback duration.
unboxedToBoxed Convert unboxed Double storage to a new strict boxed container, preserving order and values.
boxedToUnboxed Convert boxed Double values to a new unboxed array, forcing values during copying.

HMath.API.Convergence

API Purpose
StopReason Stagnation is opt-in and uses an exact-equality caller predicate; it does not reinterpret a small update as proof of a small residual.
ResidualSatisfied Declaration and type contract below.
IterationLimit Declaration and type contract below.
Stagnation Declaration and type contract below.
Convergence Iteration report retaining the estimate and residual even on a budget/stagnation stop.
Convergence Declaration and type contract below.
estimate Best current estimate, retained even when the iteration budget is exhausted.
iterationCount Number of completed updates; the initial estimate is iteration zero.
finalResidual Finite nonnegative absolute residual at the returned estimate.
stopReason ResidualSatisfied,IterationLimit,or Stagnation; successful execution does not itself imply convergence.
IterationOptions Caller-controlled iteration count and absolute/relative stopping tolerances, validated by iterateUntil.
IterationOptions Declaration and type contract below.
maximumIterations Nonnegative maximum number of updates permitted by iterateUntil.
absoluteTolerance Finite nonnegative absolute stopping threshold.
relativeTolerance Finite nonnegative tolerance scaled by the initial residual.
defaultIterationOptions Default iteration budget 1000, absolute tolerance 1e-12, relative tolerance 1e-10.
iterateUntil Stop at residual <= atol + rtol * initialResidual.
requireConvergence Given operation name then convergence report, return its estimate only for ResidualSatisfied.
resultMaybe Explicitly discard error details for callers retaining a Maybe interface.
fromMaybeError Given error value then Maybe result, convert Nothing to Left error and Just x to Right x.
Converged Read-only successful view.

HMath.API.Shape

API Purpose
Shape Scalars have shape [] and one element.
shapeDimensions Return runtime dimensions in axis order.
shapeElements Return the validated shape product, including one for scalar [] and zero when an axis is zero.
makeShape Validate nonnegative dimensions and an Int-representable element product, returning an immutable shape witness.
ScalarShape Read-only views: construction always uses makeShape.
VectorShape Declaration and type contract below.
MatrixShape Declaration and type contract below.
StaticMatrix Nominal type-indexed matrix dimensions,validated by staticMatrix.
staticMatrix Given a dynamic matrix, compare its dimensions against type-level m and n, returning a nominally indexed witness.
dynamicMatrix Forget the nominal type-level dimensions of a StaticMatrix, returning the same immutable dynamic matrix without changing its values.
staticMultiply Multiply statically compatible m-by-k and k-by-n matrices.
staticTranspose Transpose a StaticMatrix m n to StaticMatrix n m, preserving values with axes exchanged.
KnownShape Type-level list of natural dimensions, reflected without Int truncation.
reflectedShape Given a type-level shape proxy, reflect exact Integer dimensions without truncation to Int.
StaticTensor Nominal type-indexed tensor shape,validated against reflected runtime dimensions by staticTensor.
staticTensor Given dynamic tensor and type-level shape ds, return a nominal witness only if runtime dimensions match reflectedShape exactly.
dynamicTensor Forget a StaticTensor shape witness, returning its underlying immutable dynamic tensor without numerical conversion.
Coordinates Fixed-length coordinates with lawful zip Applicative.
coordinates Construct a type-indexed coordinate list only when list length equals the KnownNat index.
coordinateValues Extract the ordered list of a Coordinates n value.
coordinatesToVector Convert Coordinates n to a dynamic Vector.

HMath.Basic

API Purpose
factorial Return n! using unbounded Integer arithmetic; 0! is 1.
fibonacci Return the zero-based Fibonacci number (F0=0, F1=1).
isPrime Test an Integer by trial division through its square root.
clamp Given lower bound, upper bound, then value, return max lower (min upper value).
lerp Given endpoints a and b then parameter t, return a+(b-a)*t.

HMath.Constants

API Purpose
piConstant The circle constant pi at the target Floating precision.
eConstant Euler number exp(1) at the target Floating precision.
tau One full turn in radians, 2*pi, at target Floating precision.
goldenRatio Golden ratio (1+sqrt 5)/2 at the target Floating precision.
eulerMascheroni Euler-Mascheroni constant from the stored 50-decimal-place literal, rounded to the chosen Floating type.
catalanConstant Catalan constant from a 50-decimal-place literal, rounded to the target Floating type; distinct from the integer Catalan-number sequence.
aperyConstant Apery constant zeta(3), from a 50-decimal-place literal rounded to the chosen Floating type.
sqrt2 Positive square root of two in the target Floating type.
sqrt3 Positive square root of three in the target Floating type.
ln2 Natural logarithm of two in the target Floating type.
ln10 Natural logarithm of ten in the target Floating type.
infinity Positive IEEE infinity (1/0) for a RealFloat type.
nan IEEE not-a-number (0/0) for a RealFloat type.
Constant Exact stored decimal Rational with name,unit,provenance,measurement uncertainty,and separate approximation bound. constantAs converts the value without its metadata.
Constant Declaration and type contract below.
constantName Human-readable name of this mathematical or physical constant.
constantValue Exact Rational representation of the stored decimal value; measurement/approximation uncertainties are separate fields.
standardUncertainty Absolute one-standard-deviation measurement uncertainty; zero for definitions.
approximationBound Absolute decimal truncation bound, separate from measurement uncertainty.
constantUnit Display unit string; mathematical dimensionless constants use 1.
constantSource Provenance URL and adjustment/definition identifier for the stored value.
constantAs Convert a Constant record's exact stored Rational decimal to the target Fractional type.
mathematicalConstants Catalog of mathematical constants with names, Rational decimal values, source URLs, and absolute decimal truncation bounds of 10^-50.
physicalConstants Catalog of supported physical constants, retaining unit, source, standard measurement uncertainty, and approximation-bound metadata.
speedOfLight Speed of light in vacuum: stored value 299792458 m s^-1, absolute standard uncertainty 0, from CODATA 2022.
planckConstant Planck constant: stored value 6.62607015e-34 J s, absolute standard uncertainty 0, from CODATA 2022.
elementaryCharge Elementary charge: stored value 1.602176634e-19 C, absolute standard uncertainty 0, from CODATA 2022.
boltzmannConstant Boltzmann constant: stored value 1.380649e-23 J K^-1, absolute standard uncertainty 0, from CODATA 2022.
avogadroConstant Avogadro constant: stored value 6.02214076e23 mol^-1, absolute standard uncertainty 0, from CODATA 2022.
gravitationalConstant Newtonian constant of gravitation: stored value 6.67430e-11 m^3 kg^-1 s^-2, absolute standard uncertainty 0.00015e-11, from CODATA 2022.
electronMass Electron mass: stored value 9.1093837139e-31 kg, absolute standard uncertainty 0.0000000028e-31, from CODATA 2022.
astronomicalUnit IAU 2012 exact astronomical unit: 149597870700 metres, with zero measurement uncertainty and approximation bound.
NumericLimits Format limits and precision metadata derived from RealFloat or the explicit 16-bit format definition.
NumericLimits Declaration and type contract below.
minimumNormal Smallest positive normal value of the represented floating format.
minimumSubnormal Smallest positive subnormal value of the represented floating format.
maximumFinite Largest finite positive value of the represented floating format.
machineEpsilon Gap between one and its next larger representable value.
significandDigits Number of radix digits in the floating significand.
minimumExponent Lower exponent bound returned by RealFloat.floatRange.
maximumExponent Upper exponent bound returned by RealFloat.floatRange.
numericLimits Derived from RealFloat radixdigitsrange, not hardcoded for Double.
integerLimits Given a bounded integral type witness, return its exact (minimum,maximum) as Integers.

HMath.Error

API Purpose
MathError A failed input contract or LU numerical check.
NegativeDimensions A requested shape contains a negative dimension.
ElementCountOverflow A shape's element count exceeds maxBound :: Int.
ElementCountMismatch Expected element count, then actual element count.
ShapeMismatch Left and right shapes differ for an elementwise operation.
InnerDimensionMismatch Left column count and right row count differ for multiplication.
IndexOutOfBounds Matrix shape, then the invalid zero-based index.
SliceOutOfBounds Matrix shape, slice start, and slice extent.
VectorLengthMismatch Left and right finite-list lengths differ.
NonSquareMatrix A factorization requires equal row and column counts.
InvalidTolerance A relative pivot tolerance is negative, NaN, or infinite.
SingularMatrix An exactly zero pivot, at the given zero-based elimination step.
NearSingularMatrix A nonzero pivot is at or below the relative tolerance threshold.
NonFiniteMatrixEntry The first NaN or infinite matrix entry, in row-major order.
NonFiniteVectorEntry The first NaN or infinite vector entry, by zero-based index.
NonFiniteResult LU arithmetic produced a NaN or infinity, including overflow.
RightHandSideMismatch Expected right-hand-side row count, then actual row count.
DomainError An operation's mathematical input domain was violated.
InvalidArgument A configuration, shape, or index argument is invalid.
NonConvergence Algorithm name and exhausted iteration or evaluation budget.
RankDeficient Estimated numerical rank is insufficient for the requested solve.
NotPositiveDefinite A Cholesky pivot is not strictly positive, at a zero-based index.

HMath.Numeric

API Purpose
Int8 8-bit signed integer type
Int16 16-bit signed integer type
Int32 32-bit signed integer type
Int64 64-bit signed integer type
Word8 8-bit unsigned integer type
Word16 16-bit unsigned integer type
Word32 32-bit unsigned integer type
Word64 64-bit unsigned integer type
Float32 Alias for Haskell Float (IEEE binary32 on supported targets).
Float64 Alias for Haskell Double (IEEE binary64 on supported targets).
Complex A data type representing complex numbers.
:+ forms a complex number from its real and imaginary rectangular components.
Rational Arbitrary-precision rational numbers, represented as a ratio of two Integer values.
RoundingMode Software rounding direction: nearest-even,toward zero,toward positive infinity,or toward negative infinity.
NearestEven Declaration and type contract below.
TowardZero Declaration and type contract below.
TowardPositive Declaration and type contract below.
TowardNegative Declaration and type contract below.
NumericException Software operation flags: invalid operation,division by zero,overflow,underflow,or inexact conversion.
InvalidOperation Declaration and type contract below.
DivisionByZero Declaration and type contract below.
NumericOverflow Declaration and type contract below.
NumericUnderflow Declaration and type contract below.
Inexact Declaration and type contract below.
Rounded Rounded numeric result paired with software exception flags.
Rounded Declaration and type contract below.
roundedValue Value produced by the explicitly selected software rounding operation.
numericalExceptions Software rounding flags; these do not modify the host IEEE exception environment.
roundRational Given software rounding mode then exact Rational, return Integer rounded by nearest-even, toward zero, toward positive infinity, or toward negative infinity.
IEEEClass IEEE classification distinguishing NaN,signed infinity,signed zero,subnormal,and normal finite values.
NotANumber Declaration and type contract below.
PositiveInfinity Declaration and type contract below.
NegativeInfinity Declaration and type contract below.
PositiveZero Declaration and type contract below.
NegativeZero Declaration and type contract below.
Subnormal Declaration and type contract below.
Normal Declaration and type contract below.
classify Classify a RealFloat value as NaN, signed infinity, signed zero, subnormal, or normal.
NumericLimits Format limits and precision metadata derived from RealFloat or the explicit 16-bit format definition.
NumericLimits Declaration and type contract below.
minimumNormal Smallest positive normal value of the represented floating format.
minimumSubnormal Smallest positive subnormal value of the represented floating format.
maximumFinite Largest finite positive value of the represented floating format.
machineEpsilon Gap between one and its next larger representable value.
significandDigits Number of radix digits in the floating significand.
minimumExponent Lower exponent bound returned by RealFloat.floatRange.
maximumExponent Upper exponent bound returned by RealFloat.floatRange.
numericLimits Derived from RealFloat radixdigitsrange, not hardcoded for Double.
integerLimits Given a bounded integral type witness, return its exact (minimum,maximum) as Integers.
float16Limits Limits returned as exact binary64 values for the two 16-bit storage formats.
bfloat16Limits Limits returned as exact binary64 values for the two 16-bit storage formats.
nextAfter Adjacent representable value toward target, including gradual underflow.
frexp x=m*2^e, with abs m in [1/2,1) for nonzero finite binary inputs.
ldexp Given real value then Int exponent, scale by the numeric radix to that power using scaleFloat (binary types use powers of two).
ulpDistance IEEE binary64 distance.
withinULPs Given nonnegative allowed ULP distance then two Doubles, test their binary64 representable-value distance.
safeIntegralCast Convert an integral value to a bounded integral destination only if in range.
saturatingCast Convert an integral value to a bounded integral destination, clamping to minBound/maxBound when out of range.
realToIntegral Given software rounding mode then finite real value, round exactly through Rational then range-check the bounded integral destination.
narrowFloat A narrowing conversion must be finite and exact; choose explicit quantized Float16/BigFloat rounding APIs when loss of precision is intentional.
Float16 IEEE binary16 and bfloat16 storage.
float16 Given rounding mode then Double, round directly to IEEE binary16 and return Rounded storage plus software flags.
fromFloat16 Decode binary16 storage to Double, preserving finite values, signed zero, infinity and NaN classification.
float16Bits Return raw IEEE binary16 storage bits, including sign, exponent and fraction, as Word16.
float16FromBits Construct binary16 storage from raw Word16 without validation or rounding; all bit patterns, including NaNs, are representable.
BFloat16 Opaque bfloat16 storage with 8 exponent and 7 explicit fraction bits.
bfloat16 Given rounding mode then Double, round directly to bfloat16 without an intermediate binary32 rounding.
fromBFloat16 Decode bfloat16 storage to Double, preserving finite values, signed zero and non-finite classification.
bfloat16Bits Return raw bfloat16 storage bits as Word16.
bfloat16FromBits Construct bfloat16 storage from raw Word16 without conversion; all bit patterns are retained.
BigFloat An unbounded-exponent binary floating value backed by an exact Rational, rounded to a runtime number of significant bits (2..1,000,000).
bigFloat Given precision in [2,1000000] bits, rounding mode, then Rational, construct configurable-precision BigFloat plus Inexact flag if rounded.
bigPrecision Return the runtime number of significant binary bits retained by a BigFloat.
bigRational Return the exact Rational value of the already-rounded BigFloat, without another conversion or rounding.
bigToDouble Round BigFloat to host Double through fromRational.
bigAdd Add two BigFloats exactly then round once to the larger operand precision, nearest-even.
bigSubtract Subtract the second BigFloat from the first, rounding once nearest-even at the larger operand precision.
bigMultiply Multiply two BigFloats exactly then round once nearest-even to the larger operand precision.
bigDivide Divide two BigFloats and round once nearest-even to the larger precision.
bigSqrt Compute nonnegative BigFloat square root using integer/rational guard precision then round to the input precision.
bigExp Absolute tail controlled rational series; final rounding is accurate to the requested precision up to one final ulp, not a correctly-rounded promise.
bigLog Compute natural logarithm at the BigFloat precision using rational series and guard bits.
extended Software extended precision: 64 significant bits, unbounded exponent.
mixedAdd Given BigFloat then finite Double, add via exact Rational intermediates at max(BigFloat precision,53) bits, nearest-even.
mixedMultiply Given BigFloat then finite Double, multiply at max(BigFloat precision,53) bits using exact intermediates and nearest-even.
Fixed Runtime-scale base-ten fixed point: coefficient * 10^(-scale).
fixed Given decimal scale in [0,10000], rounding mode, then Rational, return Rounded Fixed and Inexact when required.
fixedScale Return nonnegative decimal scale s of a Fixed value; its exact value is coefficient / 10^s.
fixedCoefficient Return exact stored Integer coefficient of a Fixed value, before division by 10^fixedScale.
fixedRational Return exact coefficient/10^scale represented by a Fixed value, without rounding.
fixedAdd Add two Fixed values using the larger decimal scale, nearest-even, returning Rounded result and software flags.
fixedMultiply Given rounding mode then two Fixed values, multiply and round to their larger scale, returning Rounded result and flags.
fixedDivide Given rounding mode then Fixed numerator and denominator, divide and round to their larger scale.
Decimal Opaque decimal fixed-point value with fractional-place scale, built through decimal with explicit rounding.
decimal Given decimal fractional-place scale, rounding mode, then Rational, construct Rounded Decimal through fixed.
decimalRational Return exact Rational value stored in a Decimal without further rounding.
decimalAdd Add two Decimals at their larger decimal scale, nearest-even, returning Rounded result and software flags.
decimalMultiply Given rounding mode then two Decimals, multiply at the larger fractional-place scale and return Rounded result with flags.
decimalDivide Given rounding mode then two Decimals, divide at their larger scale and return Rounded result.
Interval Finite closed binary64 intervals.
interval Given finite lower and upper bounds in increasing order, construct a closed binary64 Interval.
intervalBounds Return (lower,upper) binary64 endpoints of a validated closed interval.
intervalAdd Add finite intervals with exact Rational endpoint arithmetic rounded outward, enclosing the exact sum.
intervalSubtract Subtract intervals with endpoints [a-d,b-c], rounding outward.
intervalMultiply Multiply intervals using the minimum/maximum of all four endpoint products and outward rounding.
intervalDivide Divide intervals using endpoint quotients with outward rounding.
intervalContains Given interval then Double, test closed-bound membership lower<=x<=upper.
Dual Forward-mode automatic differentiation, f(a+b epsilon), epsilon^2=0.
Dual Declaration and type contract below.
primal Primal component of a forward-mode Dual number.
tangent Directional derivative component of a forward-mode Dual number.
derivative Given a function on Dual numbers then primal input x, seed Dual x 1 and extract the output tangent.
Quaternion Hamilton quaternion (real, i, j, k); multiplication is noncommutative.
Quaternion Declaration and type contract below.
quaternionConjugate For Quaternion real i j k, negate the three imaginary components and preserve the real part.
quaternionNorm Return scaled Euclidean norm of four quaternion components, reducing avoidable intermediate overflow.
quaternionInverse Invert a finite nonzero quaternion using scaled norm arithmetic.
rotateVector Given nonzero finite quaternion q then (x,y,z), return imaginary part of q(0,x,y,z)inverse(q).
DualQuaternion Real and dual quaternion pair, commonly representing a rigid rotation/translation.
DualQuaternion Declaration and type contract below.
dualQuaternionMultiply Multiply real/dual quaternion pairs as (a,b)(c,d)=(ac,ad+bc).
dualQuaternionInverse Invert the real quaternion a, returning (inverse(a), -inverse(a)binverse(a)).
rigidTransform Construct a rigid transform from a nonzero rotation quaternion and translation.
transformPoint Given dual-quaternion transform then point tuple, rotate by its real part and add translation from twice the dual part times the real inverse.
kahanSum Sum a finite list using Kahan compensation; empty input yields zero.
neumaierSum Sum a finite list with Neumaier compensation, correcting for differing term magnitudes.
pairwiseSum Recursively split and sum a finite list to reduce sequential rounding accumulation.
logsumexp Empty input is -infinity; +infinity dominates finite/-infinite inputs.
sumErrorBound Conservative sequential sum bound gamma_(n-1) * sum abs x.

HMath.Scalar

API Purpose
add Add two values using their Num instance.
subtractScalar Subtract the second value from the first using Num arithmetic.
multiply Multiply two values using Num arithmetic.
divide Divide the first finite real value by the second.
quotientRemainder Return integer quotient and remainder using quotRem (quotient truncates toward zero).
euclideanDivision Euclidean remainder satisfies 0 <= r < abs divisor, for either divisor sign.
absolute Return abs using the supplied Num instance, including that instance's overflow behavior.
sign Return signum using the supplied Num instance.
minimumScalar Return the smaller of two values under their Ord instance.
maximumScalar Return the larger of two values under their Ord instance.
clampChecked Given lower bound, upper bound, then value, clamp to the closed interval.
lerpChecked Uses exact rational interpolation followed by one rounding.
inverseLerp Given endpoints a,b then value x, return (x-a)/(b-a) using rational intermediates and one conversion.
remap Given source endpoints a,b, destination endpoints c,d, then x, map x from the source interval to the destination interval.
step Given edge then x, return 0 below the edge and 1 at/above it.
smoothstep Given strictly increasing edges then x, clamp t=(x-a)/(b-a) to [0,1] and return tt(3-2*t).
smootherstep Given increasing edges then x, apply the quintic 6t^5-15t^4+10t^3 to the clamped interpolation parameter.
power Raise a finite real base to a finite real exponent using (**).
integerPower Raise a finite real base to an Integer exponent, allowing negative powers except for a zero base.
modularPower Given base, nonnegative exponent, positive modulus, compute modular exponentiation by squaring.
sqrtChecked Return the nonnegative square root of a finite nonnegative input; reject negatives/non-finite values.
cubeRoot Return the signed real cube root of a finite input, including negative values, through nthRoot 3.
nthRoot Given positive integer degree n then finite x, return its signed real n-th root.
reciprocalSqrt Return 1sqrt(x) for finite strictly positive x.
expChecked Compute exp of a finite input, reporting non-finite output as Left NonFiniteResult.
logChecked Compute the natural logarithm of finite positive x.
expm1 Compute exp(x)-1, using a convergent series near zero to reduce cancellation.
log1p Compute log(1+x), using a series near zero.
hypot Return sqrt(aa+bb) with scaling to avoid avoidable intermediate overflow.
floorChecked Convert a finite real to the greatest Integer no larger than it.
ceilChecked Convert a finite real to the least Integer no smaller than it.
roundChecked Round a finite real to Integer with ties to even, as bankersRound.
truncateChecked Convert finite real to Integer toward zero.
bankersRound Round a finite real to nearest Integer, resolving exact half ties to even.
roundDigits Decimal-place rounding with exact rational scaling and ties to even.
integerFraction Split finite x into its truncated Integer and signed fractional remainder.
positiveModulo Given integral value then strictly positive modulus, return the nonnegative remainder.
absoluteError Given actual then expected finite values, return abs(actual-expected); reject non-finite input/result.
relativeError Given actual then expected, return absolute error divided by abs(expected).
factorialChecked Return exact n! for nonnegative Integer n; negatives fail with DomainError.
doubleFactorial Return n(n-2)... exactly for n >= 0; (-1)!! is also 1.
risingFactorial Given integer x then nonnegative length n, return x(x+1)...*(x+n-1).
fallingFactorial Given integer x then nonnegative length n, return x(x-1)...*(x-n+1).
fibonacciChecked Return exact zero-based Fibonacci number using fast doubling (F0=0,F1=1).
lucas Return exact zero-based Lucas number (L0=2,L1=1).
permutations Given nonnegative n,k, return n!/(n-k)!; k>n gives zero.
combinations Given nonnegative n,k, return the exact binomial coefficient; k>n gives zero.
multinomial Given nonnegative group sizes, return factorial(sum sizes)/product(factorial sizes).
catalan Return exact n-th Catalan number for nonnegative Integer n; negative input fails.
bernoulli Bernoulli convention B1 = -1/2.
harmonic Return exact Rational sum 1+12+...+1n; n=0 gives 0 and negatives fail.
cumulativeSum Return inclusive running sums without a leading zero; output has input length.
cumulativeProduct Return inclusive running products without a leading one.
prefixSum Return running sums including a leading zero; output length is input length plus one.
fusedMultiplyAdd Software single-rounding FMA for finite inputs using exact Rational.
saturatingAdd Add bounded integers through an exact Integer intermediate and clamp to the destination minBound/maxBound.
saturatingSubtract Subtract bounded integers through Integer and clamp to type bounds instead of wrapping.
saturatingMultiply Multiply bounded integers through Integer and clamp to type bounds instead of wrapping.
checkedAdd Add bounded integers using an exact intermediate.
checkedSubtract Subtract bounded integers using an exact intermediate, returning Left DomainError on underflow/overflow.
checkedMultiply Multiply bounded integers using an exact intermediate and reject out-of-range results.
checkedFloatMultiply Report finite overflow and any nonzero exact product rounded to zero.

HMath.Trigonometry

API Purpose
sinChecked Sine of a radian argument.
cosChecked Cosine of a radian argument.
tanChecked Tangent of a radian argument; represented poles at odd pi/2 are rejected.
asinChecked Principal inverse sine in [-pi2,pi2]; require abs(x)<=1.
acosChecked Principal inverse cosine in [0,pi]; require abs(x)<=1.
atanChecked Principal inverse tangent in (-pi2,pi2).
atan2Checked Conventional atan2(y,x), range [-pi,pi].
sec Secant 1cos(x) in radians; represented odd-pi2 poles fail.
csc Cosecant 1/sin(x) in radians; represented multiples of pi fail.
cot Cotangent cos(x)/sin(x) in radians; represented multiples of pi fail.
asec Principal inverse secant acos(1/x); require abs(x)>=1.
acsc Principal inverse cosecant asin(1/x); require abs(x)>=1.
acot Inverse cotangent atan2(1,x), with range (0,pi).
sinhChecked Hyperbolic sine.
coshChecked Hyperbolic cosine.
tanhChecked Hyperbolic tangent.
asinhChecked Inverse hyperbolic sine.
acoshChecked Principal real inverse hyperbolic cosine; require x>=1.
atanhChecked Inverse hyperbolic tangent; require abs(x)<1.
sech Hyperbolic secant 1/cosh(x), using a scaled exponential formula for large arguments.
csch Hyperbolic cosecant 1/sinh(x); reject zero.
coth Hyperbolic cotangent 1/tanh(x); reject zero.
asech Inverse hyperbolic secant; require 0<x<=1.
acsch Inverse hyperbolic cosecant; reject zero and use a log formula near zero.
acoth Inverse hyperbolic cotangent; require abs(x)>1.
sincos Given a finite radian angle, return Right (sin x,cos x), propagating checked input/result failures.
wrap Wrap to [lo,hi).
normalizeAngle Wrap a finite radian angle into [0,2*pi).
normalizeSignedAngle Wrap a finite radian angle into [-pi,pi).
angleDifference Given angles a then b, return the signed wrapped difference a-b in [-pi,pi).
versine Versine 1-cos(x), evaluated as 2*sin(x/2)^2 for a radian input.
haversine Haversine sin(x/2)^2 for a radian input.
sinc Unnormalized sinc sin(x)/x for radians, with continuous value 1 at zero.
cosc (1-cos x)/x with its continuous value 0 at x=0.
greatCircleAngle Latitudes in [-pi2,pi2], longitudes any finite radians.
greatCircleDistance Given finite nonnegative sphere radius and two (latitude,longitude) radian pairs, return radius times the central angle.
sphericalSide Two spherical sides and their included angle, all in [0,pi].
sphericalAngles Interior angles for a nondegenerate minor spherical triangle, sides (0,pi).
sphericalExcess Given three side angles of a nondegenerate minor spherical triangle, compute interior-angle sum minus pi.
ComplexFunction Checked complex trigonometric/hyperbolic principal-branch function selector,including reciprocal secantcosecantcotangent variants.
CSin Declaration and type contract below.
CCos Declaration and type contract below.
CTan Declaration and type contract below.
CAsin Declaration and type contract below.
CAcos Declaration and type contract below.
CAtan Declaration and type contract below.
CSinh Declaration and type contract below.
CCosh Declaration and type contract below.
CTanh Declaration and type contract below.
CAsinh Declaration and type contract below.
CAcosh Declaration and type contract below.
CAtanh Declaration and type contract below.
CSec Declaration and type contract below.
CCsc Declaration and type contract below.
CCot Declaration and type contract below.
CSech Declaration and type contract below.
CCsch Declaration and type contract below.
CCoth Declaration and type contract below.
complexFunction Given a ComplexFunction selector then complex input, compute the selected principal-branch Data.Complex function or reciprocal.
complexSin Principal complex sine, dispatched through complexFunction.
complexCos Principal complex cosine, dispatched through complexFunction.
complexTan Principal complex tangent, dispatched through complexFunction.
complexAsin Principal complex inverse sine, dispatched through complexFunction.
complexAcos Principal complex inverse cosine, dispatched through complexFunction.
complexAtan Principal complex inverse tangent, dispatched through complexFunction.
complexSinh Principal complex hyperbolic sine, dispatched through complexFunction.
complexCosh Principal complex hyperbolic cosine, dispatched through complexFunction.
complexTanh Principal complex hyperbolic tangent, dispatched through complexFunction.
complexAsinh Principal complex inverse hyperbolic sine, dispatched through complexFunction.
complexAcosh Principal complex inverse hyperbolic cosine, dispatched through complexFunction.
complexAtanh Principal complex inverse hyperbolic tangent, dispatched through complexFunction.
periodicSawtooth Unit-amplitude periodic waves.
periodicTriangle Unit-amplitude periodic waves.
periodicSquare Unit-amplitude periodic waves.

HMath.Units

API Purpose
Dimension Opaque nine-exponent dimensional witness: seven SI bases plus data and plane-angle tags.
dimension Exponents in order length, mass, time, current, temperature, amount, luminous intensity, data, plane angle.
dimensionExponents Return nine exact integer exponents ordered as length, mass, time, current, temperature, amount, luminous intensity, data, plane angle.
dimensionless Dimension witness with all nine exponents zero; all unspecified exponents are zero.
lengthDimension Dimension witness with length exponent one; all unspecified exponents are zero.
massDimension Dimension witness with mass exponent one; all unspecified exponents are zero.
timeDimension Dimension witness with time exponent one; all unspecified exponents are zero.
temperatureDimension Dimension witness with temperature exponent one; all unspecified exponents are zero.
angleDimension Dimension witness with plane-angle tag exponent one; all unspecified exponents are zero.
dataDimension Dimension witness with data tag exponent one; all unspecified exponents are zero.
Unit Opaque exact affine unit definition SI=value*scale+offset.
unit SI = value * scale + offset.
unitName Return the display name/symbol of a Unit, for example "m".
unitDimension Return the dimensional-exponent witness of a Unit.
unitScale Return exact Rational scale in the conversion SI = value*scale + offset.
unitOffset Return exact Rational affine offset in SI = value*scale + offset.
unitProduct Multiply two zero-offset units: add dimension exponents and multiply Rational scales.
unitQuotient Divide two zero-offset units: subtract dimension exponents and divide their positive scales.
unitPower Given zero-offset Unit then Integer exponent, multiply its exponents and raise its positive scale to that power.
Quantity Opaque exact SI-valued dimensional quantity,tagging absolute temperatures separately from differences.
quantity Given Unit then Rational value, construct an exact SI-valued Quantity using its scale and offset.
temperatureDifference Given temperature Unit then Rational difference, multiply by its scale while ignoring its affine offset.
quantityDimension Return a Quantity's dimensional-exponent witness, without changing its SI value or absolute-temperature tag.
siValue Return exact Rational SI value of a Quantity.
inUnit Given destination Unit then Quantity, convert its SI value to that unit.
convert Given source Unit, destination Unit, then Rational value, convert exactly through SI.
addQuantity Add equal-dimension quantities.
subtractQuantity Subtract equal-dimension quantities.
multiplyQuantity Multiply SI values and add dimension exponents.
divideQuantity Divide SI values and subtract dimension exponents.
SIPrefix SI prefix name,symbol,and power-of-ten exponent. prefixed rejects affine units.
SIPrefix Declaration and type contract below.
prefixName SI prefix name, such as kilo.
prefixSymbol SI prefix symbol, such as k; micro uses ASCII u in this catalog.
prefixExponent Integer power of ten multiplying the base unit scale.
siPrefixes BIPM prefixes through the 2022 quettaronna and rontoquecto additions.
prefixed Given SIPrefix then zero-offset Unit, multiply its scale by 10^prefixExponent and prepend its symbol.
metre The metre Unit: 1 metre.
kilometre The kilometre Unit: 1000 metres.
centimetre The centimetre Unit: 0.01 metre.
millimetre The millimetre Unit: 0.001 metre.
inch The inch Unit: 0.0254 metre.
foot The foot Unit: 0.3048 metre.
yard The yard Unit: 0.9144 metre.
mile The mile Unit: 1609.344 metres.
nauticalMile The nauticalMile Unit: 1852 metres.
squareMetre The squareMetre Unit: 1 square metre.
hectare The hectare Unit: 10000 square metres.
cubicMetre The cubicMetre Unit: 1 cubic metre.
litre The litre Unit: 0.001 cubic metre.
millilitre The millilitre Unit: 0.000001 cubic metre.
kilogram The kilogram Unit: 1 kilogram.
gram The gram Unit: 0.001 kilogram.
tonne The tonne Unit: 1000 kilograms.
pound The pound Unit: 0.45359237 kilogram.
second The second Unit: 1 second.
minute The minute Unit: 60 seconds.
hour The hour Unit: 3600 seconds.
day The day Unit: 86400 seconds.
metresPerSecond The metresPerSecond Unit: 1 metre per second.
kilometresPerHour The kilometresPerHour Unit: 1000/3600 metres per second.
milesPerHour The milesPerHour Unit: 1609.344/3600 metres per second.
metresPerSecondSquared The metresPerSecondSquared Unit: 1 metre per second squared.
newton The newton Unit: 1 kg*m/s^2.
joule The joule Unit: 1 newton metre.
watt The watt Unit: 1 joule per second.
pascal The pascal Unit: 1 newton per square metre.
bar The bar Unit: 100000 pascals.
atmosphere The atmosphere Unit: 101325 pascals.
kelvin The kelvin Unit: absolute temperature with SI=value.
celsius The celsius Unit: absolute temperature with SI=value+273.15 kelvin.
fahrenheit The fahrenheit Unit: absolute temperature with SI=(value-32)*5/9+273.15 kelvin.
hertz The hertz Unit: 1 inverse second.
bit The bit Unit: 1 data bit.
byte The byte Unit: 8 data bits.
kibibyte The kibibyte Unit: 8192 data bits (1024 bytes).
mebibyte The mebibyte Unit: 8388608 data bits (1024^2 bytes).
gigabyte The gigabyte Unit: 8000000000 data bits (10^9 bytes).
radian The radian Unit: 1 radian.
degree The degree Unit: pi/180 radian, using the stored 50-place Rational pi approximation.
gradian The gradian Unit: pi/200 radian, using the stored Rational pi approximation.
radiansToDegrees Convert radians to degrees by multiplying by 180/pi in the chosen Floating type.
degreesToRadians Convert degrees to radians by multiplying by pi/180 in the chosen Floating type.
radiansToGradians Convert radians to gradians (400 per full turn) by multiplying by 200/pi.
gradiansToRadians Convert gradians to radians by multiplying by pi/200.