API reference

apn_mojo.float

Float provides binary floating-point arithmetic with a precision, format, rounding mode, and traps you can choose. The Float tutorial introduces the main choices; Batch covers arrays of floats. For working precision, cancellation, and certified digits, see precision and accuracy.

Floats of any precision, their formats and contexts, and correctly rounded functions, one declaration per name.

Every function computes its exact result and rounds it once. Without a context, operands merge their formats; operands that are all exact need a context, so exact arithmetic is never silently rounded. A context's traps make a call raise when its result sets the condition; nothing else reports it. Apply a function to batches with vmap, as in vmap[apn_mojo.float.sqrt]()(values, context=c).

Summary

Name Kind Summary
abs function The absolute value, in the same format.
acos function The correctly rounded arccosine, in [0, pi].
acosh function The correctly rounded inverse hyperbolic cosine.
add function The correctly rounded add, left + right.
asin function The correctly rounded arcsine, in [-pi/2, pi/2].
asinh function The correctly rounded inverse hyperbolic sine.
atan function The correctly rounded arctangent, in [-pi/2, pi/2].
atan2 function The correctly rounded angle of the point (x, y), in [-pi, pi].
atanh function The correctly rounded inverse hyperbolic tangent.
beta function Euler's beta function B(a, b) = Gamma(a) Gamma(b) / Gamma(a + b), correctly rounded (scipy's beta).
betainc function The regularized incomplete beta function I_x(a, b) = B_x(a, b) / B(a, b), correctly rounded (scipy's betainc).
betaln function The logarithm of the absolute value of Euler's beta function, log |B(a, b)|, correctly rounded (scipy's betaln).
catalan function Catalan's constant G = 0.9159..., correctly rounded.
ceil function Round a Float toward positive infinity, to an Integer (numpy's ceil).
clip function value limited to [a_min, a_max]: minimum(maximum(value, a_min), a_max) (numpy's clip), with both choices exact and one rounding; NaN in any operand gives NaN.
cos function The correctly rounded cosine.
cosh function The correctly rounded hyperbolic cosine.
digamma function The digamma function, Gamma'/Gamma, correctly rounded.
divide function The correctly rounded divide, left / right.
equal_at_precision function Whether a and b round (nearest-even) to the same value at bits bits.
erf function The error function, correctly rounded.
erfc function The complementary error function, 1 - erf, without its cancellation, correctly rounded.
erfi function The imaginary error function, -i erf(ix), correctly rounded.
erfinv function The inverse error function, the t with erf(t) = x for -1 < x < 1, correctly rounded (scipy's erfinv).
euler_e function Euler's number e = exp(1), correctly rounded.
euler_gamma function The Euler-Mascheroni constant gamma = 0.5772..., correctly rounded.
exp function The correctly rounded exponential.
exp2 function The correctly rounded 2**x.
expi function The exponential integral Ei, the principal value for x < 0, correctly rounded.
expm1 function The correctly rounded exp(x) - 1, accurate near 0.
floor function Round a Float toward negative infinity, to an Integer (numpy's floor).
fma function Fused multiply-add: a * b + c with one rounding.
fresnel function Fresnel's integrals (S(x), C(x)), each correctly rounded (scipy's fresnel).
gamma function Euler's Gamma function, correctly rounded.
gammainc function The regularized lower incomplete gamma function P(a, x) = gamma(a, x) / Gamma(a), correctly rounded (scipy's gammainc).
gammaincc function The regularized upper incomplete gamma function Q(a, x) = Gamma(a, x) / Gamma(a) = 1 - P(a, x), correctly rounded (scipy's gammaincc), computed without cancellation where Q is small.
gammaln function The logarithm of the absolute value of Gamma, log |Gamma(x)|, correctly rounded (scipy's gammaln).
hyp1f1 function Kummer's confluent hypergeometric function M(a, b, x) = sum_k (a)_k / (b)_k x**k / k!, correctly rounded (scipy's hyp1f1).
hyp2f1 function Gauss's hypergeometric function F(a, b; c; x) = sum_k (a)_k (b)_k / (c)_k x**k / k!, correctly rounded (scipy's hyp2f1), for real x <= 1 and, where it is a polynomial, every x.
lambertw function Lambert's W, the solution w of w e**w = x, correctly rounded.
ldexp function The correctly rounded value * 2**exponent.
ln2 function The natural logarithm of 2, correctly rounded.
log function The correctly rounded natural logarithm.
log10 function The correctly rounded base-10 logarithm.
log1p function The correctly rounded log(1 + x), accurate near 0.
log2 function The correctly rounded base-2 logarithm.
log2_10 function The base-2 logarithm of 10, correctly rounded.
log_ndtr function The logarithm of the standard normal distribution function, correctly rounded (scipy's log_ndtr), accurate where ndtr is near 0 or 1.
maximum function The larger of two numbers (numpy's maximum): compared exactly, the first when they are equal, and NaN when either is NaN; rounded once.
minimum function The smaller of two numbers (numpy's minimum): compared exactly, the first when they are equal, and NaN when either is NaN; rounded once.
multiply function The correctly rounded multiply, left * right.
ndtr function The standard normal distribution function, (1 + erf(x/sqrt 2)) / 2, correctly rounded (scipy's ndtr).
ndtri function The inverse of the standard normal distribution function, the x with ndtr(x) = p for 0 < p < 1, correctly rounded (scipy's ndtri).
nextafter function The next value after x in its format toward toward (numpy's nextafter).
pi function The constant pi, correctly rounded.
poch function The Pochhammer symbol (z)_m = Gamma(z + m) / Gamma(z), correctly rounded (scipy's poch).
polygamma function The polygamma function psi^(n)(x) = (-1)**(n+1) n! zeta(n+1, x), correctly rounded (scipy's polygamma); digamma for n = 0.
pow function The correctly rounded power base**exponent.
pow_int function The correctly rounded power for a signed integral exponent.
reciprocal function The correctly rounded 1 / value (numpy's reciprocal).
rootn function The correctly rounded real n-th root, IEEE 754 rootn.
round function Round a Float to the nearest Integer, a half to the even neighbour, to an Integer (numpy's round).
shichi function The hyperbolic sine and cosine integrals (Shi(x), Chi(x)), each correctly rounded (scipy's shichi).
shortest_decimal function The decimal with the fewest significant digits that reads back as x.
sici function The sine and cosine integrals (Si(x), Ci(x)), each correctly rounded (scipy's sici).
sin function The correctly rounded sine.
sin_cos function The correctly rounded sine and cosine, each rounded independently.
sinh function The correctly rounded hyperbolic sine.
spacing function The distance from x to the next value of its format away from zero, with x's sign (numpy's spacing): 2**(exponent(x) - precision) for a finite nonzero x, and the smallest positive value for a zero; NaN for infinity and NaN.
sqrt function The correctly rounded square root.
square function The correctly rounded square.
stable_hash function A 64-bit hash of the representation, stable across processes and releases.
subtract function The correctly rounded subtract, left - right.
tan function The correctly rounded tangent.
tanh function The correctly rounded hyperbolic tangent.
trunc function Round a Float toward zero, to an Integer (numpy's trunc).
ulp_distance function How many steps of the coarser format separate a and b.
zeta function The Hurwitz zeta function zeta(x, q) = sum_{k>=0} (q + k)**-x, correctly rounded (scipy's zeta); zeta(x, 1) is the Riemann zeta function at every x other than 1, its values at the non-positive integers exact.
ArithmeticContext struct The numerical choices for a rounded operation: format, rounding mode, traps, and the budget of functions whose cost depends on their input.
Float struct A binary floating-point number of any precision.
FloatFormat struct A binary precision and inclusive exponent bounds.
RoundingMode struct How an inexact result rounds: one of five named constants.
ShortestDecimal struct A decimal (-1)**negative * digits * 10**exponent10; see shortest_decimal.

Functions

abs

Source: apn_mojo/float/math.mojo

def abs(value: Float) raises -> Float

The absolute value, in the same format.

Arguments

  • value (Float): The Float.

Returns

Float: The value with its sign cleared; NaN stays NaN.

Raises

Error: Never for a valid Float.

acos

Source: apn_mojo/float/elementary.mojo

def acos(
    value: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The correctly rounded arccosine, in [0, pi].

acos(1) is +0; outside [-1, 1] the result is NaN, which is invalid.

Arguments

  • value (_FloatArgument): The operand; exact operands need a context.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the operand's format, rounded to nearest-even.

Returns

Float: The value rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact operands without a context.

acosh

Source: apn_mojo/float/elementary.mojo

def acosh(
    value: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The correctly rounded inverse hyperbolic cosine.

acosh(1) is +0; below 1 the result is NaN, which is invalid.

Arguments

  • value (_FloatArgument): The operand; exact operands need a context.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the operand's format, rounded to nearest-even.

Returns

Float: The value rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact operands without a context.

add

Source: apn_mojo/float/math.mojo

def add(
    left: _FloatArgument,
    right: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The correctly rounded add, left + right.

The exact result is rounded once. Operands may be Float, Integer, Rational, integer literals of any width or typed native numbers, in either order, and are never rounded first.

Arguments

  • left (_FloatArgument): The first operand.
  • right (_FloatArgument): The second operand.
  • context (Optional[ArithmeticContext]): The output format, rounding mode and traps; by default the merged operand formats, rounded to nearest-even.

Returns

Float: A Float in the context's format, or the merged operand format.

Raises

Error: When a trapped condition occurs, or exact operands are given without a context.

asin

Source: apn_mojo/float/elementary.mojo

def asin(
    value: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The correctly rounded arcsine, in [-pi/2, pi/2].

Outside [-1, 1] the result is NaN, which is invalid.

Arguments

  • value (_FloatArgument): The operand; exact operands need a context.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the operand's format, rounded to nearest-even.

Returns

Float: The value rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact operands without a context.

asinh

Source: apn_mojo/float/elementary.mojo

def asinh(
    value: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The correctly rounded inverse hyperbolic sine.

asinh(+-0) is +-0 and asinh(+-inf) is +-inf.

Arguments

  • value (_FloatArgument): The operand; exact operands need a context.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the operand's format, rounded to nearest-even.

Returns

Float: The value rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact operands without a context.

atan

Source: apn_mojo/float/elementary.mojo

def atan(
    value: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The correctly rounded arctangent, in [-pi/2, pi/2].

atan(+-inf) is +-pi/2 rounded.

Arguments

  • value (_FloatArgument): The operand; exact operands need a context.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the operand's format, rounded to nearest-even.

Returns

Float: The value rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact operands without a context.

atan2

Source: apn_mojo/float/elementary.mojo

def atan2(
    y: _FloatArgument,
    x: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The correctly rounded angle of the point (x, y), in [-pi, pi].

The special values are those of C99: atan2(+-0, -0) is +-pi, atan2(+-0, +0) is +-0, and infinite operands give multiples of pi/4.

Arguments

  • y (_FloatArgument): The ordinate.
  • x (_FloatArgument): The abscissa.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the merged operand formats, rounded to nearest-even.

Returns

Float: The angle rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact operands without a context.

atanh

Source: apn_mojo/float/elementary.mojo

def atanh(
    value: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The correctly rounded inverse hyperbolic tangent.

atanh(+-1) is +-inf with divide-by-zero; outside [-1, 1] the result is NaN, which is invalid.

Arguments

  • value (_FloatArgument): The operand; exact operands need a context.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the operand's format, rounded to nearest-even.

Returns

Float: The value rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact operands without a context.

beta

Source: apn_mojo/float/special.mojo

def beta(
    a: _FloatArgument,
    b: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

Euler's beta function B(a, b) = Gamma(a) Gamma(b) / Gamma(a + b), correctly rounded (scipy's beta).

Rational values, when both arguments are integers or one is a positive integer, are exact before the one rounding. At the poles it takes scipy's values: for a non-positive integer a, (-1)**b B(1 - a - b, b) when b is an integer with 1 - a - b > 0 and +inf with divide-by-zero otherwise; +0 where only a + b is a non-positive integer. B(+inf, b) is +0 for b > 0.

Arguments

  • a (_FloatArgument): The first argument; exact arguments need a context.
  • b (_FloatArgument): The second argument.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the merged argument formats, rounded to nearest-even.

Returns

Float: The value rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact arguments without a context.

betainc

Source: apn_mojo/float/special.mojo

def betainc(
    a: _FloatArgument,
    b: _FloatArgument,
    x: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The regularized incomplete beta function I_x(a, b) = B_x(a, b) / B(a, b), correctly rounded (scipy's betainc).

For a < 0, b < 0 or x outside [0, 1], and at a = b = 0 and a = b = +inf, it is NaN, which is invalid. As scipy's, it is 1 for x > 0 where a = 0 or b = +inf, 0 for x < 1 where b = 0 or a = +inf, 0 at x = 0 and 1 at x = 1. Integer parameters give exact rational values.

Arguments

  • a (_FloatArgument): The first shape; exact arguments need a context.
  • b (_FloatArgument): The second shape.
  • x (_FloatArgument): The argument.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the merged argument formats, rounded to nearest-even.

Returns

Float: The value rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact arguments without a context.

betaln

Source: apn_mojo/float/special.mojo

def betaln(
    a: _FloatArgument,
    b: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The logarithm of the absolute value of Euler's beta function, log |B(a, b)|, correctly rounded (scipy's betaln).

At the poles it is +inf where B(a, b) is infinite and -inf where it is 0, each with divide-by-zero, and exactly +0 where |B(a, b)| = 1.

Arguments

  • a (_FloatArgument): The first argument; exact arguments need a context.
  • b (_FloatArgument): The second argument.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the merged argument formats, rounded to nearest-even.

Returns

Float: The value rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact arguments without a context.

catalan

Source: apn_mojo/float/constants.mojo

def catalan(*, context: Optional[ArithmeticContext] = None) raises -> Float

Catalan's constant G = 0.9159..., correctly rounded.

Arguments

  • context (Optional[ArithmeticContext]): The format, rounding mode, traps and budget; by default 128 bits, rounded to nearest-even.

Returns

Float: G rounded once.

Raises

Error: On a trapped condition, or in an exact working format.

ceil

Source: apn_mojo/float/math.mojo

def ceil(value: Float) raises -> Integer

Round a Float toward positive infinity, to an Integer (numpy's ceil).

Arguments

  • value (Float): The operand.

Returns

Integer: The smallest Integer not below the value.

Raises

Error: For infinity and NaN.

clip

Source: apn_mojo/float/math.mojo

def clip(
    value: _FloatArgument,
    a_min: _FloatArgument,
    a_max: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

value limited to [a_min, a_max]: minimum(maximum(value, a_min), a_max) (numpy's clip), with both choices exact and one rounding; NaN in any operand gives NaN.

Arguments

  • value (_FloatArgument): The operand.
  • a_min (_FloatArgument): The lower limit.
  • a_max (_FloatArgument): The upper limit.
  • context (Optional[ArithmeticContext]): The output format, rounding mode and traps; by default the merged operand formats, rounded to nearest-even.

Returns

Float: The chosen operand in the output format.

Raises

Error: When a trapped condition occurs, or exact operands are given without a context.

cos

Source: apn_mojo/float/elementary.mojo

def cos(
    value: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The correctly rounded cosine.

cos(+-0) is exactly 1; infinities and the budget are as for sin.

Arguments

  • value (_FloatArgument): The operand; exact operands need a context.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the operand's format, rounded to nearest-even.

Returns

Float: The value rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact operands without a context.

cosh

Source: apn_mojo/float/elementary.mojo

def cosh(
    value: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The correctly rounded hyperbolic cosine.

cosh(+-0) is exactly 1 and cosh(+-inf) is +inf.

Arguments

  • value (_FloatArgument): The operand; exact operands need a context.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the operand's format, rounded to nearest-even.

Returns

Float: The value rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact operands without a context.

digamma

Source: apn_mojo/float/special.mojo

def digamma(
    value: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The digamma function, Gamma'/Gamma, correctly rounded.

digamma(+-0) is -+inf with divide-by-zero, and a negative integer or -inf gives NaN, which is invalid.

Arguments

  • value (_FloatArgument): The operand; exact operands need a context.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the operand's format, rounded to nearest-even.

Returns

Float: The value rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact operands without a context.

divide

Source: apn_mojo/float/math.mojo

def divide(
    left: _FloatArgument,
    right: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The correctly rounded divide, left / right.

The exact result is rounded once. Operands may be Float, Integer, Rational, integer literals of any width or typed native numbers, in either order, and are never rounded first. A finite nonzero value over zero is a signed infinity.

Arguments

  • left (_FloatArgument): The first operand.
  • right (_FloatArgument): The second operand.
  • context (Optional[ArithmeticContext]): The output format, rounding mode and traps; by default the merged operand formats, rounded to nearest-even.

Returns

Float: A Float in the context's format, or the merged operand format.

Raises

Error: When a trapped condition occurs, or exact operands are given without a context.

equal_at_precision

Source: apn_mojo/float/neighbors.mojo

def equal_at_precision(a: Float, b: Float, bits: Integer) raises -> Bool

Whether a and b round (nearest-even) to the same value at bits bits.

The comparison is by value, so the two zeros are equal. It rounds into the default exponent bounds, which hold every Float without overflow.

Arguments

  • a (Float): A Float that is not NaN.
  • b (Float): A Float that is not NaN.
  • bits (Integer): The precision to compare at, at least 1.

Returns

Bool: True when both round to the same value.

Raises

Error: For NaN, or when bits is not a valid precision.

erf

Source: apn_mojo/float/special.mojo

def erf(
    value: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The error function, correctly rounded.

erf(+-0) is +-0 and erf(+-inf) is +-1.

Arguments

  • value (_FloatArgument): The operand; exact operands need a context.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the operand's format, rounded to nearest-even.

Returns

Float: The value rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact operands without a context.

erfc

Source: apn_mojo/float/special.mojo

def erfc(
    value: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The complementary error function, 1 - erf, without its cancellation, correctly rounded.

erfc(+-0) is 1, erfc(+inf) is +0 and erfc(-inf) is 2.

Arguments

  • value (_FloatArgument): The operand; exact operands need a context.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the operand's format, rounded to nearest-even.

Returns

Float: The value rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact operands without a context.

erfi

Source: apn_mojo/float/special.mojo

def erfi(
    value: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The imaginary error function, -i erf(ix), correctly rounded.

erfi(+-0) is +-0 and erfi(+-inf) is +-inf.

Arguments

  • value (_FloatArgument): The operand; exact operands need a context.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the operand's format, rounded to nearest-even.

Returns

Float: The value rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact operands without a context.

erfinv

Source: apn_mojo/float/special.mojo

def erfinv(
    value: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The inverse error function, the t with erf(t) = x for -1 < x < 1, correctly rounded (scipy's erfinv).

erfinv(+-0) is +-0 and erfinv(+-1) is +-inf with divide-by-zero; beyond, and at the infinities, it is NaN, which is invalid.

Arguments

  • value (_FloatArgument): The operand; exact operands need a context.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the operand's format, rounded to nearest-even.

Returns

Float: The value rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact operands without a context.

euler_e

Source: apn_mojo/float/constants.mojo

def euler_e(*, context: Optional[ArithmeticContext] = None) raises -> Float

Euler's number e = exp(1), correctly rounded.

Arguments

  • context (Optional[ArithmeticContext]): The format, rounding mode, traps and budget; by default 128 bits, rounded to nearest-even.

Returns

Float: The constant e, rounded once.

Raises

Error: On a trapped condition, or in an exact working format.

euler_gamma

Source: apn_mojo/float/constants.mojo

def euler_gamma(*, context: Optional[ArithmeticContext] = None) raises -> Float

The Euler-Mascheroni constant gamma = 0.5772..., correctly rounded.

Arguments

  • context (Optional[ArithmeticContext]): The format, rounding mode, traps and budget; by default 128 bits, rounded to nearest-even.

Returns

Float: The constant gamma, rounded once.

Raises

Error: On a trapped condition, or in an exact working format.

exp

Source: apn_mojo/float/elementary.mojo

def exp(
    value: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The correctly rounded exponential.

exp(+-0) is exactly 1, exp(-inf) is +0, and results beyond the format overflow or underflow.

Arguments

  • value (_FloatArgument): The operand; exact operands need a context.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the operand's format, rounded to nearest-even.

Returns

Float: The value rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact operands without a context.

exp2

Source: apn_mojo/float/elementary.mojo

def exp2(
    value: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The correctly rounded 2**x.

An integral x gives the exact power of 2.

Arguments

  • value (_FloatArgument): The operand; exact operands need a context.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the operand's format, rounded to nearest-even.

Returns

Float: The value rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact operands without a context.

expi

Source: apn_mojo/float/special.mojo

def expi(
    value: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The exponential integral Ei, the principal value for x < 0, correctly rounded.

Ei(+-0) is -inf with divide-by-zero, Ei(+inf) is +inf and Ei(-inf) is -0.

Arguments

  • value (_FloatArgument): The operand; exact operands need a context.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the operand's format, rounded to nearest-even.

Returns

Float: The value rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact operands without a context.

expm1

Source: apn_mojo/float/elementary.mojo

def expm1(
    value: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The correctly rounded exp(x) - 1, accurate near 0.

expm1(+-0) is +-0 and expm1(-inf) is exactly -1.

Arguments

  • value (_FloatArgument): The operand; exact operands need a context.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the operand's format, rounded to nearest-even.

Returns

Float: The value rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact operands without a context.

floor

Source: apn_mojo/float/math.mojo

def floor(value: Float) raises -> Integer

Round a Float toward negative infinity, to an Integer (numpy's floor).

Arguments

  • value (Float): The operand.

Returns

Integer: The largest Integer not above the value.

Raises

Error: For infinity and NaN.

fma

Source: apn_mojo/float/math.mojo

def fma(
    a: _FloatArgument,
    b: _FloatArgument,
    c: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

Fused multiply-add: a * b + c with one rounding.

The exact product is added to c before the only rounding, so its cancellation and range never round early. Zero times infinity is invalid even with a NaN addend.

Arguments

  • a (_FloatArgument): The first factor.
  • b (_FloatArgument): The second factor.
  • c (_FloatArgument): The addend.
  • context (Optional[ArithmeticContext]): The output format, rounding mode and traps; by default the merged operand formats, rounded to nearest-even.

Returns

Float: a * b + c, rounded once.

Raises

Error: When a trapped condition occurs, or exact operands are given without a context.

fresnel

Source: apn_mojo/float/special.mojo

def fresnel(
    value: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Tuple[Float, Float]

Fresnel's integrals (S(x), C(x)), each correctly rounded (scipy's fresnel).

S(x) = int_0^x sin(pi t**2 / 2) dt and C(x) = int_0^x cos(pi t**2 / 2) dt. Both are +-0 at +-0 and +-1/2 at +-inf.

Arguments

  • value (_FloatArgument): The operand; exact operands need a context.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the operand's format, rounded to nearest-even.

Returns

Tuple[Float, Float]: (S(x), C(x)), each rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact operands without a context.

gamma

Source: apn_mojo/float/special.mojo

def gamma(
    value: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

Euler's Gamma function, correctly rounded.

gamma(+-0) is +-inf with divide-by-zero, a negative integer or -inf gives NaN, which is invalid, and gamma(n) is (n-1)! rounded once.

Arguments

  • value (_FloatArgument): The operand; exact operands need a context.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the operand's format, rounded to nearest-even.

Returns

Float: The value rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact operands without a context.

gammainc

Source: apn_mojo/float/special.mojo

def gammainc(
    a: _FloatArgument,
    x: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The regularized lower incomplete gamma function P(a, x) = gamma(a, x) / Gamma(a), correctly rounded (scipy's gammainc).

For a < 0 or x < 0, and at a = x = 0, it is NaN, which is invalid. P(0, x) = 1 for x > 0, P(a, 0) = 0, P(+inf, x) = 0 and P(a, +inf) = 1, as scipy's.

Arguments

  • a (_FloatArgument): The shape; exact arguments need a context.
  • x (_FloatArgument): The argument.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the merged argument formats, rounded to nearest-even.

Returns

Float: The value rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact arguments without a context.

gammaincc

Source: apn_mojo/float/special.mojo

def gammaincc(
    a: _FloatArgument,
    x: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The regularized upper incomplete gamma function Q(a, x) = Gamma(a, x) / Gamma(a) = 1 - P(a, x), correctly rounded (scipy's gammaincc), computed without cancellation where Q is small.

For a < 0 or x < 0, and at a = x = 0, it is NaN, which is invalid. Q(0, x) = 0 for x > 0, Q(a, 0) = 1, Q(+inf, x) = 1 and Q(a, +inf) = 0, as scipy's.

Arguments

  • a (_FloatArgument): The shape; exact arguments need a context.
  • x (_FloatArgument): The argument.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the merged argument formats, rounded to nearest-even.

Returns

Float: The value rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact arguments without a context.

gammaln

Source: apn_mojo/float/special.mojo

def gammaln(
    value: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The logarithm of the absolute value of Gamma, log |Gamma(x)|, correctly rounded (scipy's gammaln).

gammaln(1) and gammaln(2) are exactly +0; at 0, the negative integers and both infinities it is +inf, with divide-by-zero at the poles.

Arguments

  • value (_FloatArgument): The operand; exact operands need a context.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the operand's format, rounded to nearest-even.

Returns

Float: The value rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact operands without a context.

hyp1f1

Source: apn_mojo/float/special.mojo

def hyp1f1(
    a: _FloatArgument,
    b: _FloatArgument,
    x: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

Kummer's confluent hypergeometric function M(a, b, x) = sum_k (a)_k / (b)_k x**k / k!, correctly rounded (scipy's hyp1f1).

At a non-positive integer b it is +inf with divide-by-zero, except that a negative integer a >= b ends the series before the pole, so that hyp1f1(-n, -n, x) is the truncated exponential, as scipy's. An infinite a gives NaN, which is invalid, and an infinite b gives 1. At an infinite x it is the limit. Rational values, such as the polynomials of a non-positive integer a, are exact.

Arguments

  • a (_FloatArgument): The upper parameter; exact arguments need a context.
  • b (_FloatArgument): The lower parameter.
  • x (_FloatArgument): The argument.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the merged argument formats, rounded to nearest-even.

Returns

Float: The value rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact arguments without a context.

hyp2f1

Source: apn_mojo/float/special.mojo

def hyp2f1(
    a: _FloatArgument,
    b: _FloatArgument,
    c: _FloatArgument,
    x: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

Gauss's hypergeometric function F(a, b; c; x) = sum_k (a)_k (b)_k / (c)_k x**k / k!, correctly rounded (scipy's hyp2f1), for real x <= 1 and, where it is a polynomial, every x.

A non-positive integer a or b gives a polynomial, exact for rational arguments. At a non-positive integer c it is +inf with divide-by-zero unless the polynomial ends first; at x = 1 it is Gauss's Gamma(c) Gamma(c-a-b) / (Gamma(c-a) Gamma(c-b)) for c - a - b > 0 and +inf otherwise, as scipy's. For x > 1, where the function is not real, it is NaN, which is invalid (scipy returns +inf). Rational values, such as (1-x)**-b for c = a at a perfect power, are exact.

Arguments

  • a (_FloatArgument): The first upper parameter; exact arguments need a context.
  • b (_FloatArgument): The second upper parameter.
  • c (_FloatArgument): The lower parameter.
  • x (_FloatArgument): The argument.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the merged argument formats, rounded to nearest-even.

Returns

Float: The value rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact arguments without a context.

lambertw

Source: apn_mojo/float/special.mojo

def lambertw(
    value: _FloatArgument,
    *,
    k: Int = 0,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

Lambert's W, the solution w of w e**w = x, correctly rounded.

Branch 0 is the principal branch, defined for x >= -1/e with W >= -1; branch -1 is defined for -1/e <= x < 0 with W <= -1. W_0(+-0) is +-0 and W_0(+inf) is +inf; W_-1(+-0) is -inf with divide-by-zero. An argument outside the branch's domain gives NaN, which is invalid.

Arguments

  • value (_FloatArgument): The operand; exact operands need a context.
  • k (Int): The branch, 0 or -1.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the operand's format, rounded to nearest-even.

Returns

Float: The value rounded once.

Raises

Error: For another branch, on a trapped condition, past the budget, or for exact operands without a context.

ldexp

Source: apn_mojo/float/math.mojo

def ldexp(
    value: _FloatArgument,
    exponent: Integer,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The correctly rounded value * 2**exponent.

Arguments

  • value (_FloatArgument): The operand; exact operands need a context.
  • exponent (Integer): The power of two, of any size.
  • context (Optional[ArithmeticContext]): The output format, rounding mode and traps; by default the operand's format, rounded to nearest-even.

Returns

Float: The scaled value, rounded once.

Raises

Error: When a trapped condition occurs, or exact operands are given without a context.

ln2

Source: apn_mojo/float/constants.mojo

def ln2(*, context: Optional[ArithmeticContext] = None) raises -> Float

The natural logarithm of 2, correctly rounded.

Arguments

  • context (Optional[ArithmeticContext]): The format, rounding mode, traps and budget; by default 128 bits, rounded to nearest-even.

Returns

Float: The constant ln 2, rounded once.

Raises

Error: On a trapped condition, or in an exact working format.

log

Source: apn_mojo/float/elementary.mojo

def log(
    value: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The correctly rounded natural logarithm.

log(+-0) is -inf with divide-by-zero, log(1) is +0, and a negative argument gives NaN, which is invalid.

Arguments

  • value (_FloatArgument): The operand; exact operands need a context.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the operand's format, rounded to nearest-even.

Returns

Float: The value rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact operands without a context.

log10

Source: apn_mojo/float/elementary.mojo

def log10(
    value: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The correctly rounded base-10 logarithm.

A power of 10 gives its exact exponent; zero and negative arguments are as for log.

Arguments

  • value (_FloatArgument): The operand; exact operands need a context.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the operand's format, rounded to nearest-even.

Returns

Float: The value rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact operands without a context.

log1p

Source: apn_mojo/float/elementary.mojo

def log1p(
    value: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The correctly rounded log(1 + x), accurate near 0.

log1p(-1) is -inf with divide-by-zero; below -1 the result is NaN, which is invalid.

Arguments

  • value (_FloatArgument): The operand; exact operands need a context.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the operand's format, rounded to nearest-even.

Returns

Float: The value rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact operands without a context.

log2

Source: apn_mojo/float/elementary.mojo

def log2(
    value: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The correctly rounded base-2 logarithm.

A power of 2 gives its exact exponent; zero and negative arguments are as for log.

Arguments

  • value (_FloatArgument): The operand; exact operands need a context.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the operand's format, rounded to nearest-even.

Returns

Float: The value rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact operands without a context.

log2_10

Source: apn_mojo/float/constants.mojo

def log2_10(*, context: Optional[ArithmeticContext] = None) raises -> Float

The base-2 logarithm of 10, correctly rounded.

Arguments

  • context (Optional[ArithmeticContext]): The format, rounding mode, traps and budget; by default 128 bits, rounded to nearest-even.

Returns

Float: The constant log2(10), rounded once.

Raises

Error: On a trapped condition, or in an exact working format.

log_ndtr

Source: apn_mojo/float/special.mojo

def log_ndtr(
    value: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The logarithm of the standard normal distribution function, correctly rounded (scipy's log_ndtr), accurate where ndtr is near 0 or 1.

log_ndtr(+inf) is +0 and log_ndtr(-inf) is -inf.

Arguments

  • value (_FloatArgument): The operand; exact operands need a context.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the operand's format, rounded to nearest-even.

Returns

Float: The value rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact operands without a context.

maximum

Source: apn_mojo/float/math.mojo

def maximum(
    left: _FloatArgument,
    right: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The larger of two numbers (numpy's maximum): compared exactly, the first when they are equal, and NaN when either is NaN; rounded once.

Arguments

  • left (_FloatArgument): The first operand.
  • right (_FloatArgument): The second operand.
  • context (Optional[ArithmeticContext]): The output format, rounding mode and traps; by default the merged operand formats, rounded to nearest-even.

Returns

Float: The chosen operand in the output format, unchanged when it is a Float of that format.

Raises

Error: When a trapped condition occurs, or exact operands are given without a context.

minimum

Source: apn_mojo/float/math.mojo

def minimum(
    left: _FloatArgument,
    right: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The smaller of two numbers (numpy's minimum): compared exactly, the first when they are equal, and NaN when either is NaN; rounded once.

Arguments

  • left (_FloatArgument): The first operand.
  • right (_FloatArgument): The second operand.
  • context (Optional[ArithmeticContext]): The output format, rounding mode and traps; by default the merged operand formats, rounded to nearest-even.

Returns

Float: The chosen operand in the output format, unchanged when it is a Float of that format.

Raises

Error: When a trapped condition occurs, or exact operands are given without a context.

multiply

Source: apn_mojo/float/math.mojo

def multiply(
    left: _FloatArgument,
    right: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The correctly rounded multiply, left * right.

The exact result is rounded once. Operands may be Float, Integer, Rational, integer literals of any width or typed native numbers, in either order, and are never rounded first.

Arguments

  • left (_FloatArgument): The first operand.
  • right (_FloatArgument): The second operand.
  • context (Optional[ArithmeticContext]): The output format, rounding mode and traps; by default the merged operand formats, rounded to nearest-even.

Returns

Float: A Float in the context's format, or the merged operand format.

Raises

Error: When a trapped condition occurs, or exact operands are given without a context.

ndtr

Source: apn_mojo/float/special.mojo

def ndtr(
    value: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The standard normal distribution function, (1 + erf(x/sqrt 2)) / 2, correctly rounded (scipy's ndtr).

ndtr(+-0) is exactly 1/2, ndtr(+inf) is 1 and ndtr(-inf) is +0.

Arguments

  • value (_FloatArgument): The operand; exact operands need a context.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the operand's format, rounded to nearest-even.

Returns

Float: The value rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact operands without a context.

ndtri

Source: apn_mojo/float/special.mojo

def ndtri(
    value: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The inverse of the standard normal distribution function, the x with ndtr(x) = p for 0 < p < 1, correctly rounded (scipy's ndtri).

ndtri(1/2) is exactly +0, ndtri(0) is -inf and ndtri(1) is +inf, each with divide-by-zero; outside [0, 1] it is NaN, which is invalid.

Arguments

  • value (_FloatArgument): The probability; exact operands need a context.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the operand's format, rounded to nearest-even.

Returns

Float: The value rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact operands without a context.

nextafter

Source: apn_mojo/float/neighbors.mojo

def nextafter(x: Float, toward: _FloatArgument) raises -> Float

The next value after x in its format toward toward (numpy's nextafter).

toward may be any number and is compared with x exactly. When they are equal the result is toward (so nextafter(-0, +0) is +0); a NaN in either gives NaN. Past the largest finite value the next value is infinity, and from an infinity toward a finite value it is the largest finite value.

Arguments

  • x (Float): Any Float.
  • toward (_FloatArgument): The direction, any number.

Returns

Float: A Float in x's format.

Raises

Error: Only on a checked size error.

pi

Source: apn_mojo/float/constants.mojo

def pi(*, context: Optional[ArithmeticContext] = None) raises -> Float

The constant pi, correctly rounded.

Arguments

  • context (Optional[ArithmeticContext]): The format, rounding mode, traps and budget; by default 128 bits, rounded to nearest-even.

Returns

Float: The constant pi, rounded once.

Raises

Error: On a trapped condition (pi is never exact, so trap_inexact always raises), or in an exact working format.

poch

Source: apn_mojo/float/special.mojo

def poch(
    z: _FloatArgument,
    m: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The Pochhammer symbol (z)_m = Gamma(z + m) / Gamma(z), correctly rounded (scipy's poch).

For an integer m it is the exact product z (z+1) ... (z+m-1), or 1 / ((z-1) ... (z+m)) for m < 0, before the one rounding. It is +inf with divide-by-zero where a factor of that divisor is 0 or, for a non-integer m, where only z + m is a non-positive integer, and +0 where only z is. (+inf)_m is +inf, 1 or +0 as m is above, at or below 0.

Arguments

  • z (_FloatArgument): The first argument; exact arguments need a context.
  • m (_FloatArgument): The second argument.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the merged argument formats, rounded to nearest-even.

Returns

Float: The value rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact arguments without a context.

polygamma

Source: apn_mojo/float/special.mojo

def polygamma(
    n: Integer,
    x: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The polygamma function psi^(n)(x) = (-1)**(n+1) n! zeta(n+1, x), correctly rounded (scipy's polygamma); digamma for n = 0.

At 0 and the negative integers it is (-1)**(n+1) inf with divide-by-zero for n >= 1, as scipy's; for n < 0 it is NaN, which is invalid.

Arguments

  • n (Integer): The order, a non-negative integer.
  • x (_FloatArgument): The argument; exact arguments need a context.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the argument's format, rounded to nearest-even.

Returns

Float: The value rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact arguments without a context.

pow

Source: apn_mojo/float/elementary.mojo

def pow(
    base: _FloatArgument,
    exponent: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The correctly rounded power base**exponent.

The special values are those of C99 F.9.4.4: a zero exponent gives 1 for any base, a base of 1 gives 1 for any exponent, an integral exponent is an integer power, and a negative base with a non-integral exponent is invalid. A binary-fraction exponent can give an exact result, as in pow(16, 0.75) = 8.

Arguments

  • base (_FloatArgument): The base.
  • exponent (_FloatArgument): The exponent.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the merged operand formats, rounded to nearest-even.

Returns

Float: The power rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact operands without a context.

pow_int

Source: apn_mojo/float/math.mojo

def pow_int(
    value: _FloatArgument,
    exponent: Integer,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The correctly rounded power for a signed integral exponent.

A zero exponent gives one, even for NaN and infinity. A negative power of zero is an infinity with divide-by-zero.

Arguments

  • value (_FloatArgument): The base; exact bases need a context.
  • exponent (Integer): The exponent, of any size.
  • context (Optional[ArithmeticContext]): The output format, rounding mode and traps; by default the operand's format, rounded to nearest-even.

Returns

Float: value ** exponent, rounded once.

Raises

Error: When a trapped condition occurs, or exact operands are given without a context.

reciprocal

Source: apn_mojo/float/math.mojo

def reciprocal(
    value: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The correctly rounded 1 / value (numpy's reciprocal).

Arguments

  • value (_FloatArgument): The operand; exact operands need a context.
  • context (Optional[ArithmeticContext]): The output format, rounding mode and traps; by default the operand's format, rounded to nearest-even.

Returns

Float: The reciprocal, rounded once.

Raises

Error: When a trapped condition occurs, or an exact operand is given without a context.

rootn

Source: apn_mojo/float/elementary.mojo

def rootn(
    value: _FloatArgument,
    n: Int,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The correctly rounded real n-th root, IEEE 754 rootn.

An odd root keeps the sign, an even root of a negative value is NaN, which is invalid, and a zero's root is that zero (+0 for an even n). A root that is a binary fraction is exact.

Arguments

  • value (_FloatArgument): The operand; exact operands need a context.
  • n (Int): The degree, at least 1.
  • context (Optional[ArithmeticContext]): The output format, rounding mode and traps; by default the operand's format, rounded to nearest-even.

Returns

Float: The root rounded once.

Raises

Error: When n is below 1 (use pow), on a trapped condition, or for exact operands without a context.

round

Source: apn_mojo/float/math.mojo

def round(value: Float) raises -> Integer

Round a Float to the nearest Integer, a half to the even neighbour, to an Integer (numpy's round).

Arguments

  • value (Float): The operand.

Returns

Integer: The nearest Integer: 2.5 gives 2, 3.5 gives 4 and -2.5 gives -2.

Raises

Error: For infinity and NaN.

shichi

Source: apn_mojo/float/special.mojo

def shichi(
    value: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Tuple[Float, Float]

The hyperbolic sine and cosine integrals (Shi(x), Chi(x)), each correctly rounded (scipy's shichi).

Shi(x) = int_0^x sinh(t)/t dt and Chi(x) = gamma + log x + int_0^x (cosh(t) - 1)/t dt for x > 0. Shi(+-0) is +-0 and Shi(+-inf) is +-inf; Chi(+-0) is -inf with divide-by-zero, Chi(+inf) is +inf, and for a negative argument Chi is NaN, which is invalid.

Arguments

  • value (_FloatArgument): The operand; exact operands need a context.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the operand's format, rounded to nearest-even.

Returns

Tuple[Float, Float]: (Shi(x), Chi(x)), each rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact operands without a context.

shortest_decimal

Source: apn_mojo/float/shortest.mojo

def shortest_decimal(
    x: Float,
    *,
    limits: Optional[ConversionLimits] = None,
) raises -> ShortestDecimal

The decimal with the fewest significant digits that reads back as x.

Reading back rounds to nearest-even in x's format. Among the decimals with that many digits, the result is the one closest to x, and on a tie the one with an even last digit. For binary64 values this is the decimal Python's repr prints, except at the smallest value: a format has no subnormals, so every value from half the smallest value up to it reads back as it, and 2e-308 is the shortest decimal of 2**-1022.

The search is exact: the values that round to x form an interval, and a binary search finds the largest power of ten whose multiples meet it.

Arguments

  • x (Float): A finite Float.
  • limits (Optional[ConversionLimits]): Optional per-call conversion limits; see ConversionLimits.

Returns

ShortestDecimal: The sign, the digits and the decimal exponent.

Raises

Error: For infinity and NaN, or when the digits exceed limits.

sici

Source: apn_mojo/float/special.mojo

def sici(
    value: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Tuple[Float, Float]

The sine and cosine integrals (Si(x), Ci(x)), each correctly rounded (scipy's sici).

Si(x) = int_0^x sin(t)/t dt and Ci(x) = gamma + log x + int_0^x (cos(t) - 1)/t dt for x > 0. Si(+-0) is +-0 and Si(+-inf) is +-pi/2, correctly rounded; Ci(+-0) is -inf with divide-by-zero, Ci(+inf) is +0, and for a negative argument Ci is NaN, which is invalid.

Arguments

  • value (_FloatArgument): The operand; exact operands need a context.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the operand's format, rounded to nearest-even.

Returns

Tuple[Float, Float]: (Si(x), Ci(x)), each rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact operands without a context.

sin

Source: apn_mojo/float/elementary.mojo

def sin(
    value: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The correctly rounded sine.

sin(+-0) is +-0 and an infinity gives NaN, which is invalid. A huge argument needs about as many bits of pi as its exponent; past the context's budget the function raises.

Arguments

  • value (_FloatArgument): The operand; exact operands need a context.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the operand's format, rounded to nearest-even.

Returns

Float: The value rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact operands without a context.

sin_cos

Source: apn_mojo/float/elementary.mojo

def sin_cos(
    value: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Tuple[Float, Float]

The correctly rounded sine and cosine, each rounded independently.

Arguments

  • value (_FloatArgument): The operand; exact operands need a context.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the operand's format, rounded to nearest-even.

Returns

Tuple[Float, Float]: (sin(value), cos(value)).

Raises

Error: On a trapped condition, past the budget, or for exact operands without a context.

sinh

Source: apn_mojo/float/elementary.mojo

def sinh(
    value: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The correctly rounded hyperbolic sine.

sinh(+-0) is +-0 and sinh(+-inf) is +-inf.

Arguments

  • value (_FloatArgument): The operand; exact operands need a context.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the operand's format, rounded to nearest-even.

Returns

Float: The value rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact operands without a context.

spacing

Source: apn_mojo/float/neighbors.mojo

def spacing(x: Float) raises -> Float

The distance from x to the next value of its format away from zero, with x's sign (numpy's spacing): 2**(exponent(x) - precision) for a finite nonzero x, and the smallest positive value for a zero; NaN for infinity and NaN.

A format has no subnormals, so in the lowest precision - 1 binades the spacing is below the smallest positive value and cannot be represented.

Arguments

  • x (Float): Any Float.

Returns

Float: The signed spacing, in x's format.

Raises

Error: When the spacing is below the smallest positive value of the format.

sqrt

Source: apn_mojo/float/math.mojo

def sqrt(
    value: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The correctly rounded square root.

-0 stays -0; a negative nonzero value gives NaN, which is invalid.

Arguments

  • value (_FloatArgument): The operand; exact operands need a context.
  • context (Optional[ArithmeticContext]): The output format, rounding mode and traps; by default the operand's format, rounded to nearest-even.

Returns

Float: The square root, rounded once.

Raises

Error: When a trapped condition occurs, or exact operands are given without a context.

square

Source: apn_mojo/float/math.mojo

def square(
    value: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The correctly rounded square.

Arguments

  • value (_FloatArgument): The operand; exact operands need a context.
  • context (Optional[ArithmeticContext]): The output format, rounding mode and traps; by default the operand's format, rounded to nearest-even.

Returns

Float: value * value, rounded once.

Raises

Error: When a trapped condition occurs, or exact operands are given without a context.

stable_hash

Source: apn_mojo/float/math.mojo

def stable_hash(x: Float) -> UInt64

A 64-bit hash of the representation, stable across processes and releases.

The algorithm is APNH-64: tag 3, then the precision, the exponent bounds, the class and the sign, and for a finite nonzero value the exponent and the significand. Unlike Mojo's Hasher, its output never changes, so stored hashes stay valid. It hashes representations, as FloatKey compares them: 0.0 and -0.0, or 1 at 53 and at 128 bits, hash differently.

Arguments

  • x (Float): The Float.

Returns

UInt64: The hash.

subtract

Source: apn_mojo/float/math.mojo

def subtract(
    left: _FloatArgument,
    right: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The correctly rounded subtract, left - right.

The exact result is rounded once. Operands may be Float, Integer, Rational, integer literals of any width or typed native numbers, in either order, and are never rounded first.

Arguments

  • left (_FloatArgument): The first operand.
  • right (_FloatArgument): The second operand.
  • context (Optional[ArithmeticContext]): The output format, rounding mode and traps; by default the merged operand formats, rounded to nearest-even.

Returns

Float: A Float in the context's format, or the merged operand format.

Raises

Error: When a trapped condition occurs, or exact operands are given without a context.

tan

Source: apn_mojo/float/elementary.mojo

def tan(
    value: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The correctly rounded tangent.

tan(+-0) is +-0; infinities and the budget are as for sin.

Arguments

  • value (_FloatArgument): The operand; exact operands need a context.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the operand's format, rounded to nearest-even.

Returns

Float: The value rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact operands without a context.

tanh

Source: apn_mojo/float/elementary.mojo

def tanh(
    value: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The correctly rounded hyperbolic tangent.

tanh(+-inf) is exactly +-1.

Arguments

  • value (_FloatArgument): The operand; exact operands need a context.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the operand's format, rounded to nearest-even.

Returns

Float: The value rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact operands without a context.

trunc

Source: apn_mojo/float/math.mojo

def trunc(value: Float) raises -> Integer

Round a Float toward zero, to an Integer (numpy's trunc).

Arguments

  • value (Float): The operand.

Returns

Integer: The integer part.

Raises

Error: For infinity and NaN.

ulp_distance

Source: apn_mojo/float/neighbors.mojo

def ulp_distance(a: Float, b: Float) raises -> Integer

How many steps of the coarser format separate a and b.

Both round (nearest-even) to the smaller of the two precisions; the result is the number of representable values strictly between them, plus one if they differ, so equal values give 0 and neighbours 1. The two zeros are equal, and each infinity is one step beyond the largest finite value.

Arguments

  • a (Float): A Float that is not NaN.
  • b (Float): A Float that is not NaN, with the same exponent bounds as a.

Returns

Integer: The nonnegative distance.

Raises

Error: For NaN, or when the exponent bounds differ.

zeta

Source: apn_mojo/float/special.mojo

def zeta(
    x: _FloatArgument,
    q: _FloatArgument,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Float

The Hurwitz zeta function zeta(x, q) = sum_{k>=0} (q + k)**-x, correctly rounded (scipy's zeta); zeta(x, 1) is the Riemann zeta function at every x other than 1, its values at the non-positive integers exact.

It is defined for x > 1 (every x other than 1 when q = 1), takes a negative q only for an integer x, and is +inf with divide-by-zero at x = 1 and at the non-positive integers q; elsewhere it is NaN, which is invalid.

Arguments

  • x (_FloatArgument): The exponent; exact arguments need a context.
  • q (_FloatArgument): The shift.
  • context (Optional[ArithmeticContext]): The output format, rounding mode, traps and budget; by default the merged argument formats, rounded to nearest-even.

Returns

Float: The value rounded once.

Raises

Error: On a trapped condition, past the budget, or for exact arguments without a context.

Structs

ArithmeticContext

Source: apn_mojo/float/context.mojo

struct ArithmeticContext(ImplicitlyCopyable, Writable)

The numerical choices for a rounded operation: format, rounding mode, traps, and the budget of functions whose cost depends on their input.

A context is a value passed to each call; there is no global or thread-local context, and making one changes nothing elsewhere. A trapped condition makes the call raise, naming the condition, and nothing is published. Math functions report conditions only through traps: there is no status argument or sticky flag. NaN results and exact special results are not inexact, and division by zero signals only divide-by-zero.

A correctly rounded transcendental function such as exp works at a higher precision until its result is certain; max_precision bounds that working precision, and a function that would need more raises an error naming it.

Implements

Copyable, ImplicitlyCopyable, Writable

ArithmeticContext.__init__ { #ArithmeticContext.init .api-name }

def __init__(
    out self,
    *,
    format: Optional[FloatFormat] = None,
    rounding: RoundingMode = RoundingMode.nearest_even,
    trap_inexact: Bool = False,
    trap_underflow: Bool = False,
    trap_overflow: Bool = False,
    trap_divide_by_zero: Bool = False,
    trap_invalid: Bool = False,
    max_precision: Optional[Int] = None,
) raises

A context; every argument is optional.

Arguments

  • format (Optional[FloatFormat]): The output format; FloatFormat() (128 bits) by default.
  • rounding (RoundingMode): The rounding mode.
  • trap_inexact (Bool): Raise when a result is rounded.
  • trap_underflow (Bool): Raise when a result is tiny and inexact.
  • trap_overflow (Bool): Raise when a result exceeds the format's range.
  • trap_divide_by_zero (Bool): Raise when a finite value is divided by zero.
  • trap_invalid (Bool): Raise when a result is an invalid NaN.
  • max_precision (Optional[Int]): The largest working precision, in bits, that a correctly rounded function may use; by default max(8 * p, p + 4096) for an output precision p.

Raises

Error: When rounding is not one of the named constants, or max_precision is below 1.

ArithmeticContext.format

def format(self) -> FloatFormat

The output format.

Returns

FloatFormat: The format.

ArithmeticContext.max_precision

def max_precision(self) -> Optional[Int]

The budget of correctly rounded functions, if one is set.

Returns

Optional[Int]: The largest working precision in bits, or None for the default.

ArithmeticContext.rounding

def rounding(self) -> RoundingMode

The rounding mode.

Returns

RoundingMode: The mode.

ArithmeticContext.traps_divide_by_zero

def traps_divide_by_zero(self) -> Bool

Whether division by zero raises.

Returns

Bool: The trap setting.

ArithmeticContext.traps_inexact

def traps_inexact(self) -> Bool

Whether inexact results raise.

Returns

Bool: The trap setting.

ArithmeticContext.traps_invalid

def traps_invalid(self) -> Bool

Whether invalid operations raise.

Returns

Bool: The trap setting.

ArithmeticContext.traps_overflow

def traps_overflow(self) -> Bool

Whether overflow raises.

Returns

Bool: The trap setting.

ArithmeticContext.traps_underflow

def traps_underflow(self) -> Bool

Whether underflow raises.

Returns

Bool: The trap setting.

ArithmeticContext.write_to

def write_to(self, mut writer: Some[Writer])

Write the format, rounding mode and traps.

Arguments

  • writer (mut Some[Writer]): The destination.

Float

Source: apn_mojo/float/value.mojo

struct Float(
    Absable,
    Boolable,
    Equatable,
    ImplicitlyCopyable,
    Writable,
    _FloatComparison,
    _FloatSource,
    _BatchElement,
)

A binary floating-point number of any precision.

A finite nonzero value is (-1)**s * m * 2**(e - p): a significand m of exactly p bits and an exponent e within its format's bounds. Every operation computes the exact result and rounds it once. Zeros and infinities are signed; NaN is canonical and signless.

Operation Contract
x + y, x - y, x * y, x / y One nearest-even rounding of the exact result
x ** n Signed integral power, nearest-even, in x's format
+x, -x, abs(x) Exact, same format
x += y and the other compound forms Round into x's format; x unchanged on error
==, !=, <, <=, >, >= Exact comparison of the stored values; NaN is unordered
Bool(x) False only for either zero

Without a context, operands merge their formats: exact operands contribute no precision, a native float its precision (Float64: 53 bits) and a Float its precision and exponent bounds, which must match. Quiet NaN propagates without signaling; 0/0, inf/inf, 0 * inf and inf - inf are invalid; a finite nonzero value over zero is a signed infinity with divide-by-zero. An exact cancellation is +0, or -0 when rounding toward negative.

Printing shows exact hexadecimal, such as 0x3p0 for 3 and 0x1p-1 for one half, without the format; JSON keeps both value and format.

Limitations

Bare decimal literals are rejected: write Float("0.1") for the exact decimal or Float(Float64(0.1)) for the binary64 value. A native number cannot be the left operand of a comparison. Float is not hashable; use FloatKey for dictionary keys. Int(x) and Float64(x) are unavailable; use the named conversions.

Implements

Absable, Boolable, Copyable, Equatable, ImplicitlyCopyable, Writable, _BatchElement, _FloatComparison, _FloatSource, _MapArgument

Float.__init__ { #Float.init .api-name }

def __init__(out self, *, context: Optional[ArithmeticContext] = None) raises

Positive zero; in the context's format, or 128 bits by default.

Arguments

  • context (Optional[ArithmeticContext]): The format of the zero.

Raises

Error: Only on an invalid context.

def __init__[ T: Copyable ](
    out self,
    value: T,
    *,
    context: Optional[ArithmeticContext] = None,
) raises

Round an exact number to a Float.

An Integer, Rational, Float or Complex-free exact value is rounded once, directly to the format. A Float keeps its own format unless a context is given.

Parameters

  • T (Copyable): The source type.

Arguments

  • value (T): The value to convert.
  • context (Optional[ArithmeticContext]): The output format, rounding mode and traps; by default 128 bits, or the Float's own format.

Raises

Error: When a trapped condition occurs or the source type is not numeric.

def __init__(
    out self,
    text: String,
    *,
    context: Optional[ArithmeticContext] = None,
    allow_whitespace: Bool = False,
    allow_underscores: Bool = False,
    limits: Optional[ConversionLimits] = None,
) raises

Parse exact decimal, hexadecimal or binary text and round it once.

Decimal text takes an optional e exponent (1.25e-3); 0x and 0b text requires a p binary exponent (0x1.8p2). inf and nan are accepted in any case. The whole source is rounded once, with no native intermediate.

Arguments

  • text (String): The number.
  • context (Optional[ArithmeticContext]): The output format, rounding mode and traps; 128 bits by default.
  • allow_whitespace (Bool): Accept surrounding ASCII whitespace.
  • allow_underscores (Bool): Accept single underscores between digits.
  • limits (Optional[ConversionLimits]): Optional per-call conversion limits; see ConversionLimits.

Raises

Error: When the text is not a valid number, naming the byte offset; on a trapped condition; or when it exceeds limits.

3 more overloads

Round an integer literal of any width once to the format.

def __init__(
    out self,
    value: IntLiteral,
    *,
    context: Optional[ArithmeticContext] = None,
) raises

Convert a typed native number exactly, then round once; Float64 subnormals and signed zeros keep their values.

def __init__[ dtype: DType ](
    out self,
    value: SIMD[dtype, 1],
    *,
    context: Optional[ArithmeticContext] = None,
) raises

Rejects bare decimal literals, explaining the exact and binary64 alternatives.

def __init__(
    out self,
    value: FloatLiteral,
    *,
    context: Optional[ArithmeticContext] = None,
) raises

Float.ceil

def ceil(self) raises -> Integer

Round toward positive infinity, to an Integer.

Returns

Integer: The smallest Integer not below the value.

Raises

Error: For infinity and NaN.

Float.exponent

def exponent(self) raises -> Int

The normalized exponent e of a finite nonzero value.

Returns

Int: The exponent, with value = significand * 2**(exponent - precision).

Raises

Error: For zero, infinity and NaN.

Float.floor

def floor(self) raises -> Integer

Round toward negative infinity, to an Integer.

Returns

Integer: The largest Integer not above the value.

Raises

Error: For infinity and NaN.

Float.format

def format(self) -> FloatFormat

The stored format.

Returns

FloatFormat: The precision and exponent bounds.

Float.from_json

def from_json(
    text: String,
    *,
    limits: Optional[ConversionLimits] = None,
) raises -> Self

Read a Float from its version-1 JSON record, without rounding.

Arguments

  • text (String): The JSON record.
  • limits (Optional[ConversionLimits]): Optional per-call conversion limits; see ConversionLimits.

Returns

Self: The Float the record holds, in the record's format.

Raises

Error: When the text is not exactly that schema or is not canonical.

Float.from_native

def from_native[ dtype: DType ](
    value: SIMD[dtype, 1],
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Self

Convert a typed native number exactly, then round once.

Parameters

  • dtype (DType): The native type.

Arguments

  • value (SIMD[dtype, 1]): The native value.
  • context (Optional[ArithmeticContext]): The output format, rounding mode and traps.

Returns

Self: The Float.

Raises

Error: On a trapped condition or an unsupported type.

1 more overload

Convert a native `Int` exactly, then round once.

def from_native(
    value: Int,
    *,
    context: Optional[ArithmeticContext] = None,
) raises -> Self

Float.infinity

def infinity(
    *,
    negative: Bool = False,
    context: Optional[ArithmeticContext] = None,
) raises -> Self

A signed infinity.

Arguments

  • negative (Bool): Whether the infinity is negative.
  • context (Optional[ArithmeticContext]): Its format; 128 bits by default.

Returns

Self: The infinity.

Raises

Error: Only on an invalid context.

Float.is_finite

def is_finite(self) -> Bool

Whether the value is zero or finite.

Returns

Bool: False for infinities and NaN.

Float.is_infinite

def is_infinite(self) -> Bool

Whether the value is an infinity.

Returns

Bool: True for +inf and -inf.

Float.is_integer

def is_integer(self) -> Bool

Whether the value is a finite integer (Python's float.is_integer).

Returns

Bool: True for both zeros and for finite values without a fractional part; False for infinities and NaN.

Float.is_nan

def is_nan(self) -> Bool

Whether the value is NaN.

Returns

Bool: True for NaN.

Float.is_zero

def is_zero(self) -> Bool

Whether the value is either zero.

Returns

Bool: True for +0 and -0.

Float.nan

def nan(*, context: Optional[ArithmeticContext] = None) raises -> Self

The canonical quiet NaN.

Arguments

  • context (Optional[ArithmeticContext]): Its format; 128 bits by default.

Returns

Self: NaN.

Raises

Error: Only on an invalid context.

Float.parse

def parse(
    text: String,
    *,
    context: Optional[ArithmeticContext] = None,
    allow_whitespace: Bool = False,
    allow_underscores: Bool = False,
    limits: Optional[ConversionLimits] = None,
) raises -> Self

Parse text; the same contract as the text constructor.

Arguments

  • text (String): The number.
  • context (Optional[ArithmeticContext]): The output format, rounding mode and traps.
  • allow_whitespace (Bool): Accept surrounding ASCII whitespace.
  • allow_underscores (Bool): Accept single underscores between digits.
  • limits (Optional[ConversionLimits]): Optional per-call conversion limits; see ConversionLimits.

Returns

Self: The parsed Float.

Raises

Error: When the text is not a valid number, on a trapped condition, or when it exceeds limits.

Float.precision

def precision(self) -> Int

The significand precision in bits.

Returns

Int: The format's precision.

Float.representation_cmp

def representation_cmp(self, other: Self) -> Int

Compare representations in a strict total order.

Values come first, in the total_cmp order; equal values then order by precision, then by the lower and the upper exponent bound, each ascending. Sorting by this order gives the same result from any input order.

Arguments

  • other (Self): The other Float.

Returns

Int: -1, 0 or 1; 0 exactly when same_representation holds.

Float.round

def round(self) raises -> Integer

Round to the nearest Integer, and a half to the even neighbour.

Returns

Integer: The nearest Integer: 2.5 gives 2, 3.5 gives 4, -2.5 gives -2 and 0.5 gives 0.

Raises

Error: For infinity and NaN.

Float.same_representation

def same_representation(self, other: Self) -> Bool

Whether two Floats are the same representation, not just equal values.

== compares values, so 0.0 == -0.0, NaN equals nothing, and 1 at 53 and 128 bits are equal. Representations differ in each of those cases: they match when class, sign, precision, exponent bounds, exponent and significand all do. NaN is canonical, so the NaNs of one format match.

Arguments

  • other (Self): The other Float.

Returns

Bool: True when every part of the representation matches.

Float.sign

def sign(self) raises -> Int

The sign: -1, 0 or 1.

Returns

Int: -1 for negative values, 0 for zeros, 1 for positive values.

Raises

Error: For NaN.

Float.signbit

def signbit(self) -> Bool

Whether the sign is negative, including negative zero.

Returns

Bool: The sign bit; false for NaN.

Float.significand

def significand(self) raises -> Integer

The significand m of a finite value.

Returns

Integer: A nonnegative Integer with exactly precision() bits; zero for zeros.

Raises

Error: For infinity and NaN.

Float.to_format

def to_format(
    self,
    format: FloatFormat,
    *,
    rounding: RoundingMode = RoundingMode.nearest_even,
) raises -> Self

Round to another format.

Increasing precision keeps the value; it cannot recover information lost earlier. Different exponent bounds may underflow or overflow.

Arguments

  • format (FloatFormat): The new format.
  • rounding (RoundingMode): The rounding mode.

Returns

Self: A new Float in format.

Raises

Error: Only on an invalid rounding mode.

Float.to_integer_exact

def to_integer_exact(self) raises -> Integer

Convert an integral value to Integer.

Returns

Integer: The equal Integer.

Raises

Error: When the value has a fractional part, or is infinite or NaN.

Float.to_json

def to_json(self, *, limits: Optional[ConversionLimits] = None) raises -> String

Write the version-1 JSON record: the value and its complete format.

Arguments

  • limits (Optional[ConversionLimits]): Optional per-call conversion limits; see ConversionLimits.

Returns

String: Compact canonical JSON; see the conversion chapter for the schema.

Raises

Error: When the output exceeds limits.

Float.to_native

def to_native[ dtype: DType ](
    self,
    *,
    rounding: RoundingMode = RoundingMode.nearest_even,
) raises -> SIMD[dtype, 1]

Round to a native floating-point type.

Rounds directly, subnormals included, with no intermediate Float64.

Parameters

  • dtype (DType): float16, bfloat16, float32 or float64.

Arguments

  • rounding (RoundingMode): The rounding mode.

Returns

SIMD[dtype, 1]: The rounded native value.

Raises

Error: When dtype is not a supported floating-point type.

Float.to_native_exact

def to_native_exact[dtype: DType](self) raises -> SIMD[dtype, 1]

Convert to a native type without loss.

Floating-point targets keep signed zero, infinity and NaN; integral targets require a finite integral value in range.

Parameters

  • dtype (DType): A native floating-point or integral type.

Returns

SIMD[dtype, 1]: The same value in the native type.

Raises

Error: When the conversion would round or the value does not fit.

Float.to_rational_exact

def to_rational_exact(self) raises -> Rational

The exact value as a Rational, in lowest terms.

A finite Float is a binary fraction, so the conversion never rounds; both zeros give 0. Rational(x) is the same conversion.

Returns

Rational: The Rational with the same value.

Raises

Error: For infinity and NaN, or when the value would exceed addressable storage.

Float.to_string

def to_string(
    self,
    base: Int = 10,
    *,
    notation: StaticString = "auto",
    digits: Optional[Int] = None,
    rounding: RoundingMode = RoundingMode.nearest_even,
    limits: Optional[ConversionLimits] = None,
) raises -> String

Write the value as text, by default as print does.

Base 10 writes the shortest decimal that reads back as this Float, or with digits significant digits rounded with rounding. notation lays it out: auto (the default) is positional from 1e-6 up to but excluding 1e21 (0.00001, 3.0) and scientific beyond (1e+21); positional and scientific force one. hexadecimal, or base 16, writes the exact value (0x3p0); base 2 writes it in binary.

Arguments

  • base (Int): 10 for decimal, 16 or 2 for the exact value.
  • notation (StaticString): auto, positional, scientific or hexadecimal.
  • digits (Optional[Int]): The significant digits of a decimal, at least one; by default the fewest that read back as this Float.
  • rounding (RoundingMode): The rounding mode with digits.
  • limits (Optional[ConversionLimits]): Optional per-call conversion limits; see ConversionLimits.

Returns

String: The text.

Raises

Error: When the base, notation or options are invalid, or the output exceeds limits.

Float.total_cmp

def total_cmp(self, rhs: Self) -> Int

Compare in the total order.

The order is negative infinity, negative finite values, -0, +0, positive finite values, positive infinity, NaN. Equal values in different formats tie.

Arguments

  • rhs (Self): The other Float.

Returns

Int: -1, 0 or 1.

Float.trunc

def trunc(self) raises -> Integer

Round toward zero, to an Integer.

Returns

Integer: The integer part.

Raises

Error: For infinity and NaN.

Float.write_to

def write_to(self, mut writer: Some[Writer])

Write the shortest decimal that reads back as this Float, as print does: positional from 1e-6 up to but excluding 1e21, scientific beyond (see to_string). A value too long for the default conversion limits is written in exact hexadecimal.

Arguments

  • writer (mut Some[Writer]): The destination.

Float.zero

def zero(
    *,
    negative: Bool = False,
    context: Optional[ArithmeticContext] = None,
) raises -> Self

A signed zero.

Arguments

  • negative (Bool): Whether the zero is negative.
  • context (Optional[ArithmeticContext]): Its format; 128 bits by default.

Returns

Self: The zero.

Raises

Error: Only on an invalid context.

FloatFormat

Source: apn_mojo/float/context.mojo

struct FloatFormat(Equatable, ImplicitlyCopyable, Writable)

A binary precision and inclusive exponent bounds.

A finite nonzero value in the format is (-1)**s * m * 2**(e - p) with m of exactly p bits and emin <= e <= emax; the smallest positive value is 2**(emin - 1). There are no subnormals. Making a format allocates nothing.

Implements

Copyable, Equatable, ImplicitlyCopyable, Writable

Aliases

  • MAX_PRECISION
  • DEFAULT_EMIN
  • DEFAULT_EMAX

FloatFormat.__init__ { #FloatFormat.init .api-name }

def __init__(
    out self,
    precision: Int = 128,
    *,
    emin: Int = DEFAULT_EMIN,
    emax: Int = DEFAULT_EMAX,
) raises

A format with precision bits and the given exponent bounds.

Arguments

  • precision (Int): Significand bits, from 1 to FloatFormat.MAX_PRECISION.
  • emin (Int): The smallest normalized exponent.
  • emax (Int): The largest normalized exponent, at least emin.

Raises

Error: When the precision or bounds are out of range.

FloatFormat.binary32

def binary32() raises -> Self

IEEE 754 binary32 (single): 24 bits, exponents -125 through 128.

It covers the normal range of a Float32; there are no subnormals, so the smallest positive value is 2**-126.

Returns

Self: The format.

Raises

Error: Never in practice; the bounds are valid.

FloatFormat.binary64

def binary64() raises -> Self

IEEE 754 binary64 (double): 53 bits, exponents -1021 through 1024.

It covers the normal range of a Float64; there are no subnormals, so the smallest positive value is 2**-1022.

Returns

Self: The format.

Raises

Error: Never in practice; the bounds are valid.

FloatFormat.emax

def emax(self) -> Int

The largest normalized exponent.

Returns

Int: emax.

FloatFormat.emin

def emin(self) -> Int

The smallest normalized exponent.

Returns

Int: emin.

FloatFormat.precision

def precision(self) -> Int

The significand precision in bits.

Returns

Int: The precision.

FloatFormat.write_to

def write_to(self, mut writer: Some[Writer])

Write the precision and bounds.

Arguments

  • writer (mut Some[Writer]): The destination.

RoundingMode

Source: apn_mojo/float/context.mojo

struct RoundingMode(Equatable, ImplicitlyCopyable, Writable)

How an inexact result rounds: one of five named constants.

nearest_even (the default) rounds to the nearest value, and a tie to the even one; toward_zero, toward_positive, toward_negative and away_from_zero are directed. At the boundary between zero and the smallest value, a tie chooses zero.

Implements

Copyable, Equatable, ImplicitlyCopyable, Writable

Aliases

  • nearest_even
  • toward_zero
  • toward_positive
  • toward_negative
  • away_from_zero

RoundingMode.write_to

def write_to(self, mut writer: Some[Writer])

Write the constant's name, such as nearest_even.

Arguments

  • writer (mut Some[Writer]): The destination.

ShortestDecimal

Source: apn_mojo/float/shortest.mojo

struct ShortestDecimal(ImplicitlyCopyable, Writable)

A decimal (-1)**negative * digits * 10**exponent10; see shortest_decimal.

Implements

Copyable, ImplicitlyCopyable, Writable

ShortestDecimal.digits

def digits(self) -> String

The decimal digits, without leading or trailing zeros.

Returns

String: The digits; "0" for a zero.

ShortestDecimal.exponent10

def exponent10(self) -> Int

The power of ten that scales the digits.

Returns

Int: The exponent; 0 for a zero.

ShortestDecimal.negative

def negative(self) -> Bool

The sign, including that of a negative zero.

Returns

Bool: True for a negative value or -0.

ShortestDecimal.write_to

def write_to(self, mut writer: Some[Writer])

Write the value as digits and a decimal exponent, such as 3141592653589793e-15, which reads back as the same Float.

Arguments

  • writer (mut Some[Writer]): The destination.

Format selection

If you omit the context, arithmetic combines the operand formats as follows:

  • Integers, rationals, and integer literals contribute no precision bits.
  • Native floats contribute their significand precision: 11 bits for Float16, 8 for BFloat16, 24 for Float32, and 53 for Float64. They impose no exponent bounds.
  • Library Floats contribute their stored precision and exponent bounds. Bounds must agree when no context overrides them.

An ArithmeticContext sets the output format, rounding mode, and traps. To keep a value's format while choosing other settings, use format=value.format(). Compound assignments keep their destination format. Top-level arithmetic on exact inputs stays exact unless a context requests a Float result.

Bare decimal literals are not accepted as floating-point inputs. Use Float("0.1") to round the decimal value directly, or Float(Float64(0.1)) to import the native float's existing binary approximation.

Special values

Operators use nearest-even rounding without condition traps. Named functions accept contexts that can trap inexact, underflow, overflow, divide-by-zero, and invalid conditions. Status is internal; there is no mutable global flag set.

Quiet NaNs propagate. 0/0, inf/inf, 0 * inf, and inf - inf produce NaN and the invalid condition. A finite nonzero value divided by signed zero gives a signed infinity and divide-by-zero. Multiplication and division combine signs with XOR. Like-signed zeros add to that sign; opposite zeros and exact cancellation give negative zero only when rounding toward negative infinity.

sqrt(-0) is negative zero. A negative nonzero square-root input produces NaN and invalid. Any value to the zeroth power is one, including NaN and infinity. Odd powers preserve the sign of a negative zero or infinity; even powers clear it. Integral conversions reject NaNs and infinities.

Comparisons

Comparisons use the exact stored values, without rounding them to a common format. Their exponent bounds need not match. Integer and rational comparisons are exact. The two zero signs compare equal; NaN compares unequal to every value, including itself. total_cmp provides a total ordering of values.

Float has no hash under this equality. To cache values by representation, use FloatKey. It distinguishes formats and zero signs, and treats a canonical NaN in one format as the same key. For direct representation comparisons, use same_representation and representation_cmp. See representation identity.

With typed native numbers, put the library value on the left of the comparison or explicitly convert the native value to an appropriate library type.

Native output

to_native[dtype]() rounds directly to Float16, BFloat16, Float32, or Float64, including native subnormals, with a selected rounding mode. to_native_exact[dtype]() raises when an exact conversion is impossible. to_rational_exact() returns the stored finite binary fraction exactly.

floor, ceil, and trunc produce integers in the named direction. round rounds to the nearest integer with ties to even, as NumPy's does, and is_integer() tests for an integral value.

Text and JSON

Floats print the shortest decimal that reads back as the same value in their format: 0.1, 3.0, 0.00001. From 1e-6 up to but excluding 1e21 the notation is positional, beyond it scientific, as JavaScript prints numbers: 1e-07, 1.1805916207174113e+21. Zero, infinity, and NaN print as 0.0, -0.0, inf, -inf, or nan. to_string() writes the same text and takes options: notation="positional", "scientific" or "hexadecimal", and digits=n with a rounding mode. Hexadecimal text, also to_string(16), shows the exact value: 0x3p0 is 3, and 0x1p-1 is one half. Text omits precision and exponent bounds; JSON keeps the format as well as the value.

float_interchange.mojo Download
"""Float JSON that keeps every bit."""

from apn_mojo import Float, Rational, FloatFormat, ArithmeticContext, ConversionLimits


def main() raises:
    var context = ArithmeticContext(format=FloatFormat(3, emin=-10, emax=10))
    var value = Float(Rational(-1, 3), context=context)
    print("hex:", value.to_string(16))
    print("binary:", value.to_string(2))
    var record = value.to_json()
    print(record)
    var restored = Float.from_json(record)
    print("same value and format:", restored == value, restored.format() == value.format())
    print("bounded output:", value.to_string(16, limits=ConversionLimits(max_output_bytes=7)))
    var zero = Float.from_json(Float.zero(negative=True, context=context).to_json())
    print("negative zero:", zero, zero.signbit())

Run from the repository root pixi run mojo run -I src docs/examples/float_interchange.mojo

Output

hex: -0x5p-4
binary: -0b101p-4
{"version":1,"family":"float","precision":"3","emin":"-10","emax":"10","class":"finite","sign":"-","significand":"5","exponent":"-1"}
same value and format: True True
bounded output: -0x5p-4
negative zero: -0.0 True

Decimal text accepts e exponents. Hexadecimal (0x) and binary (0b) text use p exponents for powers of two. A decimal printed by a Float reads back exactly with that Float's format: Float(text, context=ArithmeticContext(format=x.format())). shortest_decimal finds the shortest decimal that rounds back to the same value in the target format under nearest-even rounding. Consult its declaration for the result object and limits.

Large decimal conversions can require large working buffers. Use ConversionLimits where input size is not controlled. JSON details are in Conversion and interchange.

Formats, rounding and traps

A finite nonzero value is (-1)**s * m * 2**(e - p), with a p-bit significand and emin <= e <= emax. Formats have no subnormals: values below 2**(emin - 1) round to zero or the smallest positive value. Nearest-even is the default; a tie halfway between zero and that smallest value goes to zero.

float_formats.mojo Download
"""Formats, rounding modes and traps."""

from apn_mojo import ArithmeticContext, FloatFormat, RoundingMode


def main() raises:
    var format = FloatFormat(173, emin=-1000, emax=1000)
    var context = ArithmeticContext(
        format=format,
        rounding=RoundingMode.toward_positive,
        trap_overflow=True,
    )
    print(format)
    print("precision:", context.format().precision())
    print("rounding:", context.rounding())
    print("trap overflow:", context.traps_overflow())
    print("default precision:", FloatFormat().precision())

Run from the repository root pixi run mojo run -I src docs/examples/float_formats.mojo

Output

FloatFormat(precision=173, emin=-1000, emax=1000)
precision: 173
rounding: toward_positive
trap overflow: True
default precision: 128

The five modes are nearest_even, toward_zero, toward_positive, toward_negative, and away_from_zero. The last always rounds an inexact magnitude upward; it is not a ties-away nearest mode.

FloatFormat.binary32() and .binary64() use the corresponding native normal ranges and precisions, but still have no subnormals. nextafter, spacing (signed, as NumPy's), ulp_distance, and equal_at_precision inspect spacing and neighboring values; see their declarations for zero, range, and NaN rules.

A trapped condition raises before the destination changes. Ordered reductions can trap at an intermediate step, while exact sum and dot apply traps to their final result. See ordered reductions.

Elementary functions

exp, expm1, exp2, log, log1p, log2, log10, sin, cos, tan, sin_cos, atan, asin, acos, atan2, sinh, cosh, tanh, asinh, acosh, atanh, pow and rootn round correctly in every mode: each result is the exact value rounded once, as MPFR gives it. Special values follow C99 Annex F: NaN propagates without a flag, poles such as log(0) and atanh(1) are infinities with divide-by-zero, and arguments outside the domain give NaN, which is invalid. Only trivial results are exact, such as exp(0) = 1, log2(2**k) = k, rootn(-27, 3) = -3 and pow(16, 0.75) = 8; exact Rational arguments such as 1/3 are evaluated exactly, never rounded first.

A function increases its working precision until it can certify the rounding. The context's max_precision sets the ceiling, by default max(8 * p, p + 4096). If a call needs more, it raises an error naming the function, argument, and budget. Huge arguments to sin, cos and tan are the cases that approach this ceiling: argument reduction needs about as many bits of pi as the argument's exponent. See Correct rounding.

Constants

pi, euler_e, ln2, log2_10, euler_gamma and catalan return the constant correctly rounded to the context, using 128 bits and nearest-even rounding by default. Up to 4096 bits, ln 2 and pi come from compiled tables; the other constants and wider precisions are computed on each call. The library does not cache them at run time. For enclosing balls, see apn_mojo.ball.

Special functions

gamma, gammaln, digamma, erf, erfc, erfi, expi, sici, shichi, fresnel, lambertw, ndtr, log_ndtr, erfinv and ndtri, the two-argument beta, betaln, poch, zeta, polygamma, gammainc and gammaincc, the three-argument hyp1f1 and betainc, and the four-argument hyp2f1 use scipy.special's names. Like the elementary functions, they round correctly in every mode and accept exact Integer and Rational arguments. sici, shichi and fresnel return pairs.

Special values follow MPFR where it has the function (gamma, lgamma, digamma, erf, erfc and eint), scipy at the poles of the gamma ratios, and the limits otherwise: gamma(n) is (n-1)! rounded once, gamma(+-0) is +-inf with divide-by-zero, and a negative integer gives NaN. gammaln is log |Gamma|, +inf at 0 and the negative integers. Ci and Chi are defined for x > 0, so a negative argument gives NaN. Fresnel's integrals are normalized as S(x) = int_0^x sin(pi t**2 / 2) dt. lambertw(x, k=0) is the principal branch, defined for x >= -1/e; k=-1 is the lower branch on [-1/e, 0). ndtr(x) = (1 + erf(x/sqrt 2))/2 is exactly 1/2 at 0, and log_ndtr keeps its relative accuracy where ndtr is near 0 or 1.

beta(a, b), betaln(a, b) = log |B(a, b)| and poch(z, m) = Gamma(z+m)/Gamma(z) are exact before their one rounding where the value is rational: B(a, b) when both arguments are integers or one is a positive integer, (z)_m for an integer m. At the poles they follow scipy: for a non-positive integer a, B(a, b) is the limit (-1)**b B(1-a-b, b) when b is an integer with 1 - a - b > 0 and +inf with divide-by-zero otherwise, and 0 where only a + b is a non-positive integer; (z)_m is +inf where a factor of its divisor is 0 or, for a non-integer m, where only z + m is a non-positive integer, and 0 where only z is.

zeta(x, q) is the Hurwitz zeta function on scipy's domain, x > 1, with a negative q only for an integer x, and +inf at x = 1 and at the non-positive integers q; zeta(x, 1) (and the package-level zeta(x)) is the Riemann zeta function at every x other than 1, exact at the non-positive integers. polygamma(n, x) = (-1)**(n+1) n! zeta(n+1, x) takes an Integer order, is digamma for n = 0, and is (-1)**(n+1) inf at the poles, as scipy's. hyp1f1(a, b, x) is Kummer's M(a, b, x), scipy's unregularized function: +inf at the non-positive integers b, except that a negative integer a >= b ends the series before the pole (so hyp1f1(-n, -n, x) is the truncated exponential), NaN for an infinite a, 1 for an infinite b, and the limit at an infinite x. Its rational values, such as the polynomials of a non-positive integer a and hyp1f1(2, 4, 2) = 3, are exact. gammainc(a, x) and gammaincc(a, x) are the regularized incomplete gamma functions P and Q = 1 - P, each without cancellation. They are NaN for a < 0 or x < 0 and at a = x = 0, with scipy's values at a = 0, x = 0 and the infinities. hyp2f1(a, b, c, x) is Gauss's F for real x <= 1, and a polynomial at every x when a or b is a non-positive integer. It is +inf at the non-positive integers c that the polynomial does not end before, and at x = 1 with c - a - b <= 0, as scipy's. For x > 1 otherwise it is NaN, which is invalid; scipy returns +inf there. betainc(a, b, x) is the regularized incomplete beta function, with scipy's values at the edges, and exact for integer shapes. erfinv and ndtri invert erf and ndtr on (-1, 1) and (0, 1), with +-inf at the ends and NaN beyond.

The methods and their error bounds are in Correct rounding.