moonnum

    Python's numbers for MoonBit.

    number
    numbers
    numeric
    bigint
    big-integer
    arbitrary-precision
    fixed-point
    bigfloat
    arbitrary-precision-float
    multiprecision
    mpmath
    high-precision
    floating-point
    nan
    infinity
    rounding
    decimal
    transcendental
    exp
    ln
    sqrt
    pi
    trigonometry
    integer
    float
    ieee754
    complex
    complex-numbers
    fraction
    rational
    numeric-tower
    math
    python
    moonbit
    Download zip
    Version
    0.2.5
    License
    Apache-2.0
    Last updated
    18 days ago
    Downloads
    303

    No dependencies

    #moonnum

    Numbers in MoonBit that behave the way you expect them to.

    Arbitrary-precision integers, IEEE-754 floats with honest text, complex numbers written 3+4j, exact fractions, and a real carried to any width — one package, one error type, one formatting language.

    let n = @moonnum.parse_int("0xff_ec", base=0) // 65516, any base, any size
    let z = @moonnum.parse_complex("3+4j") // (3+4j)
    let f = @moonnum.parse_fraction("0.1") // 1/10, exactly

    @moonnum.repr_float(0.1 + 0.2) // "0.30000000000000004"
    @moonnum.format(f, ".3%") // "10.000%"

    Nothing in here rounds behind your back. 0.1 as a fraction is one tenth; 0.1 as a float is the double it really is, and says so when asked:

    @moonnum.repr_float(0.1) // "0.1" shortest string that reads back
    @moonnum.float_hex(0.1) // "0x1.999999999999ap-4"
    @moonnum.as_ratio(0.1) // 3602879701896397/36028797018963968
    @moonnum.repr_float(0.1 + 0.2) // "0.30000000000000004"
    @moonnum.format(@moonnum.parse("22/7"), ".6f") // "3.142857", exactly rounded

    #Install

    moon add moonbitstack/moonnum

    import { "moonbitstack/moonnum" }

    Runs on wasm, wasm-gc, js and native.

    #The four kinds

    Number holds any of the four and does the mixing:

    let third = @moonnum.parse("1/3")
    let total = @moonnum.parse("1") + third + @moonnum.parse("0.5") // 11/6
    let judged = @moonnum.parse("1") == @moonnum.parse("1.0") // true

    Promotion follows the tower — integer, fraction, float, complex — and comparison is exact: 9007199254740993 is greater than 9007199254740992.0, which a float-first comparison gets wrong.

    #A real with a width

    The four kinds above are exact where they can be and binary where they must be. There is a fifth type for the case in between — a real carried at a precision the caller chooses, for the series and the expansions that a double cannot finish:

    let bits = @moonnum.Fixed::bits_for_digits(50)
    let two = @moonnum.Fixed::of_int(2, bits)
    two.sqrt().to_string() // 1.41421356237309504880168872420969807856967187537695
    two.sqrt() * two.sqrt() < two // true: each step truncates
    (two * @moonnum.Fixed::pi(bits)).to_decimal(10) // 6.2831853072
    @moonnum.parse_fixed("1e-3", bits) catch { _ => two } // text from outside, refused with where it stopped

    Fixed is mantissa / 2^bits: fixed point, so the rounding of every step is one truncation and a whole computation carries one width. It has + - * /, comparison, sqrt, exp, ln, a real pow, sin, cos, atan, and pi/ln2 to as many digits as the width holds. An operation keeps the left operand's width and brings the right one to it; at changes a value's width. of_scaled(digits, places) seeds it from a decimal constant, of_decimal reads a literal a program carries, parse_fixed reads one from outside, and to_decimal(places) writes it back.

    A value outside an operation's domain, such as the square root of a negative number, stops the program with the reason, as an integer division by zero does: these are written with operators, which cannot raise.

    It is not one of the Number kinds, and that is deliberate: those are widthless, and a value here is only as good as the width a caller chose for it.

    #A real carried to any width

    The four kinds are widthless: an integer has as many digits as it needs, a float has exactly fifty-three, a fraction is exact or is not. BigFloat is the case in between — mantissa * 2^exponent, with the width the value was rounded to kept beside it, so every value keeps the same count of digits wherever it sits on the line.

    let c = @moonnum.Context::new(200)
    let two = @moonnum.BigFloat::of_int(2, context=c)

    two.sqrt(context=c).to_significant(60) // 1.41421356237309504880168872420969807856967187537694807317668
    @moonnum.BigFloat::pi(context=c).to_significant(60)
    // 3.14159265358979323846264338327950288419716939937510582097494
    two.pow(@moonnum.BigFloat::of_double(0.5), context=c) // the same as sqrt

    An operator keeps the wider of its two operands and rounds to nearest even: the answer is as good as what went into it and no better. A Context is a width and a direction together, and the five directions are the ones mpmath names — nearest even, floor, ceiling, toward zero, away from zero.

    @moonnum.Rounding::Nearest // ties to the even digit
    @moonnum.Rounding::Floor // toward minus infinity
    @moonnum.Rounding::Ceiling // toward plus infinity
    @moonnum.Rounding::Down // toward zero
    @moonnum.Rounding::Up // away from zero

    let flinch = @moonnum.Context::new(53, rounding=@moonnum.Rounding::Up)
    flinch.add(@moonnum.BigFloat::one(), @moonnum.BigFloat::parse("1e-100")) // 1.0000000000000002

    sqrt, exp, ln, pow — and expm1 and log1p, which are the same two answers taken without ever forming the one that would swallow a small argument — the circular and the hyperbolic functions are all there, computed at the width asked for from series and formulas — pi is Machin's, ln 2 is two arctangents of a third, e is the exponential of one. Nothing in the source is a table of digits that could go stale, and a thousand digits costs a few thousand terms and nothing else.

    Kind is what a value is: Finite, PositiveInfinity, NegativeInfinity, NotANumber. A square root of a negative, a logarithm of a negative and a quotient of zero by zero answer the NaN; a quotient by zero answers an infinity, and divide is the same quotient for a caller who would rather be told.

    A value goes into and out of the other shapes the library already has — @bigint.BigInt, Fixed, Double, decimal text — and a double makes the round trip unchanged, since every finite double is a binary fraction already.

    #When the answer is complex

    sqrt(-1) answers nan, and that is the right answer for a type that holds real numbers. The value exists anyway, and it is one promotion away — written out at the call site, because a function whose type is a real should not quietly return something else:

    let c = @moonnum.Context::new(200)
    let minus_one = -@moonnum.BigFloat::one(context=c)

    minus_one.to_complex().sqrt(context=c) // 0 + 1j, where sqrt(-1) was nan
    minus_one.to_complex().ln(context=c) // 0 + pi*j
    @moonnum.BigComplex::new(two, zero).asin(context=c) // pi/2 - 1.3169...*j

    BigComplex is two BigFloats and the elementary functions on them. The branches are the principal ones and the cut is read from above, which is the only side a type without a signed zero can spell; the reference implementation has no signed zero either, so the two agree without a table of exceptions. Division is a function that refuses, like Fraction::divide; a complex power is exp(w ln z) with a whole real exponent taken by squaring, so an integer power stays exact. to_complex is exact and to_real refuses a value whose imaginary part is not zero, rather than dropping it.

    #Arithmetic

    OnFunctions
    integersfloordiv, floor_mod, divmod, power (with modulus~), gcd, lcm, isqrt, factorial, comb, perm, bit_length, to_bytes, of_bytes
    floatsround_float(d, ndigits~), round_big, floor_big, ceil_big, trunc_big, as_ratio, as_integer_ratio
    complex+ - *, Complex::divide, Complex::pow, abs, conjugate
    fractions+ - *, Fraction::divide, Fraction::pow, compare, floor_big, ceil_big, round, round_big, to_double, limit_denominator
    any of themNumber::add, Number::sub, Number::mul, Number::divide, Number::pow, compare_numeric, equal_numeric
    BigFloat+ - * /, divide, abs, sqrt, exp, expm1, ln, log1p, pow, sin, cos, tan, asin, acos, atan, sinh, cosh, tanh, asinh, acosh, atanh, round, pi, e, ln2, to_complex
    BigComplex+ - *, divide, abs, arg, conjugate, sqrt, exp, ln, pow, sin, cos, tan, asin, acos, atan, sinh, cosh, tanh, asinh, acosh, atanh, to_real

    Fraction::pow takes an integer exponent and stays a ratio — (2/3) ** 100 is an exact numerator over an exact denominator — while Number::pow follows the tower and gives a float when an exponent is one.

    #Reading

    FunctionReads
    parse_int(text, base~ = 10)int(s, base): prefixes when base is 0, single underscores between digits, surrounding whitespace
    parse_float(text)float(s): inf, infinity, nan in any case, decimal and exponent forms, underscores
    parse_complex(text)complex(s): 1+2j, (1+2j), j, -j, 1e3j — and 3+5i
    parse_fraction(text)Fraction(s): 3/4, -1.25, 1e-3, 7
    parse(text)a Number of whichever kind the literal spells
    BigFloat::parse(text, context?)a decimal at a width: inf, infinity, nan, exponents, underscores, surrounding whitespace

    #Writing

    FunctionWrites
    repr_float(d)the shortest string that reads back, switching to an exponent at 1e16 and 1e-5
    float_hex(d) / float_of_hex(s)the exact hexadecimal form, and back
    repr_complex(z), repr_fraction(f)(1+2j), 2j, Fraction(3, 4)
    format(value, spec)the format-specification mini-language, for any kind
    to_stringas many digits as the width speaks for — fifteen at 53 bits, sixty at 200 — trailing zeros dropped
    to_decimal(places), to_significant(digits)an exact count of places, or of significant digits

    #The format language

    [[fill]align][sign][z][#][0][width][grouping][.precision][type]

    @moonnum.format_int(1234567N, "015,d") // "000,001,234,567"
    @moonnum.format_int(255N, "#010_x") // "0x000_00ff"
    @moonnum.format_float(0.25, ".2%") // "25.00%"
    @moonnum.format_float(-0.0, "z") // "0.0"
    z.format(".2f") // "3.00+4.00j"

    Types b c d e E f F g G n o x X % and no type at all; fill and alignment < > ^ =; sign + - space; # alternate form; 0 zero padding that participates in grouping; grouping , and _, four digits to a group for binary, octal and hexadecimal.

    #Arithmetic that can fail, fails on purpose

    One error type, four cases, no panics:

    pub(all) suberror Refused {
    Malformed(at~ : Int, reason~ : String) // where the text stopped making sense
    ZeroDivision
    Overflow(reason~ : String)
    Domain(reason~ : String)
    }

    let half = @moonnum.parse_fraction("1/2")
    let bad : String = half.divide(@moonnum.parse_fraction("0")).to_string() catch {
    @moonnum.ZeroDivision => "no"
    _ => "no"
    }

    at counts UTF-16 code units, so it can be used to slice the input directly. Division is a function and not an operator (Fraction::divide, Complex::divide) because MoonBit's Div trait cannot raise, and a numeric library that panics on zero is worse than one that says so.

    #What this is not

    • Not a decimal type. Decimal has a context, signals and rounding modes; that is a different problem.
    • Not a bignum encoding. Variable-length integer encodings live elsewhere.
    • Not complex math. cmath's functions are out until something needs them.
    • Not a fifth kind in Number. The tower's kinds are widthless, and a BigFloat is only as good as the width it carries, so it stands beside the tower rather than in it.

    #Documentation

    • Tutorial — six pages, one per kind plus formatting and the real of any width. Every output block on them was produced by running the code above it, including the refusals.
    • API reference — every public item.
    • Design notes — how the digits are produced, and why the tower compares exactly.
    • src/examples/ — moon run src/examples/01-integers and friends.

    #Licence

    Apache-2.0.

    Refused

    pub(all) suberror Refused {
    Malformed(at~ : Int, reason~ : String)
    ZeroDivision
    Overflow(reason~ : String)
    Domain(reason~ : String)
    }

    Everything this library refuses, in one type.

    Malformed carries the offset where the input stopped making sense, in UTF-16 code units — the unit StringView indexes by — so a caller can point at the character instead of at the string.
    impl Show for Refused

    Refused::output

    fn Refused::output(self : Refused, logger : &Logger) -> Unit

    Refused::to_string

    fn Refused::to_string(self : Refused) -> String

    BigComplex

    pub(all) struct BigComplex {
    real : BigFloat
    imag : BigFloat
    }

    A complex number: z.real + z.imag * j, both parts carried at whatever width they were given.

    The two parts are independent BigFloats, so a width is a property of each part rather than of the pair; an operation rounds both to the width it is told, which for the operators is the wider of the two operands.

    This is not Complex generalised. Complex is fifty-three bits with C11 Annex G's signed zeros and infinity recovery; this one has no signed zero at all — BigFloat cannot spell one — so it reads a branch cut from the upper side and follows the principal branches mpmath uses.
    impl Add for BigComplex
    impl Eq for BigComplex
    impl Mul for BigComplex
    impl Neg for BigComplex
    impl Show for BigComplex
    impl Sub for BigComplex

    BigComplex::abs

    fn BigComplex::abs(self : BigComplex, context? : Context) -> BigFloat

    The modulus, sqrt(re^2 + im^2), rounded at the context's width.

    An infinite part makes it infinite: a modulus is a distance, and a distance to a point at infinity is not a question without an answer.

    BigComplex::acos

    fn BigComplex::acos(self : BigComplex, context? : Context) -> BigComplex

    acos z at the context's width and direction.

    BigComplex::acosh

    fn BigComplex::acosh(self : BigComplex, context? : Context) -> BigComplex

    acosh z at the context's width and direction.

    BigComplex::add

    fn BigComplex::add(self : BigComplex, other : BigComplex) -> BigComplex

    BigComplex::arg

    fn BigComplex::arg(self : BigComplex, context? : Context) -> BigFloat

    The argument in (-pi, pi], the principal value atan2(im, re).

    A point on the negative real axis has argument pi and not -pi: the cut is read from the side approaching from above, which is the only side this type can spell.

    BigComplex::asin

    fn BigComplex::asin(self : BigComplex, context? : Context) -> BigComplex

    asin z at the context's width and direction.

    BigComplex::asinh

    fn BigComplex::asinh(self : BigComplex, context? : Context) -> BigComplex

    asinh z at the context's width and direction.

    BigComplex::atan

    fn BigComplex::atan(self : BigComplex, context? : Context) -> BigComplex

    atan z at the context's width and direction.

    BigComplex::atanh

    fn BigComplex::atanh(self : BigComplex, context? : Context) -> BigComplex

    atanh z at the context's width and direction.

    BigComplex::conjugate

    fn BigComplex::conjugate(self : BigComplex) -> BigComplex

    The conjugate: the same distance from the origin, on the other side of the real axis.

    BigComplex::cos

    fn BigComplex::cos(self : BigComplex, context? : Context) -> BigComplex

    cos z at the context's width and direction.

    BigComplex::cosh

    fn BigComplex::cosh(self : BigComplex, context? : Context) -> BigComplex

    cosh z at the context's width and direction.

    BigComplex::default

    fn BigComplex::default() -> BigComplex

    BigComplex::divide

    fn BigComplex::divide(self : BigComplex, other : BigComplex, context? : Context) -> BigComplex raise Refused

    z / w at the given width.

    Refuses a zero divisor, as Fraction::divide and Complex::divide do: Div cannot raise, so the operator is not offered for this type and the division that can fail is a function.

    BigComplex::equal

    fn BigComplex::equal(self : BigComplex, other : BigComplex) -> Bool

    BigComplex::exp

    fn BigComplex::exp(self : BigComplex, context? : Context) -> BigComplex

    e^z at the context's width and direction.

    BigComplex::j

    fn BigComplex::j(context? : Context) -> BigComplex

    The imaginary unit at a width.

    BigComplex::ln

    fn BigComplex::ln(self : BigComplex, context? : Context) -> BigComplex

    ln z at the context's width and direction.

    BigComplex::mul

    fn BigComplex::mul(self : BigComplex, other : BigComplex) -> BigComplex

    The product, on the type, so that z * w works without importing the trait.

    BigComplex::neg

    fn BigComplex::neg(self : BigComplex) -> BigComplex

    BigComplex::new

    fn BigComplex::new(real : BigFloat, imag : BigFloat) -> BigComplex

    BigComplex(real, imag), with both parts exactly as given.

    BigComplex::not_equal

    fn BigComplex::not_equal(x : BigComplex, y : BigComplex) -> Bool

    BigComplex::of_real

    fn BigComplex::of_real(value : BigFloat) -> BigComplex

    A real value as a complex one, without going through an instance.

    BigComplex::output

    fn BigComplex::output(self : BigComplex, logger : &Logger) -> Unit

    BigComplex::pow

    fn BigComplex::pow(self : BigComplex, exponent : BigComplex, context? : Context) -> BigComplex raise Refused

    z^w, on the principal branch: exp(w ln z), with a whole real exponent taken by squaring instead.

    Refuses 0 raised to a negative or a non-real power, the one place a complex power has no answer at all rather than an infinity: ln 0 is not a number on the branch this type follows.

    BigComplex::precision

    fn BigComplex::precision(self : BigComplex) -> Int

    The width an operation inherits when the caller does not name one: the wider of the two parts.

    BigComplex::sin

    fn BigComplex::sin(self : BigComplex, context? : Context) -> BigComplex

    sin z at the context's width and direction.

    BigComplex::sinh

    fn BigComplex::sinh(self : BigComplex, context? : Context) -> BigComplex

    sinh z at the context's width and direction.

    BigComplex::sqrt

    fn BigComplex::sqrt(self : BigComplex, context? : Context) -> BigComplex

    sqrt z at the context's width and direction.

    BigComplex::sub

    fn BigComplex::sub(self : BigComplex, other : BigComplex) -> BigComplex

    BigComplex::tan

    fn BigComplex::tan(self : BigComplex, context? : Context) -> BigComplex

    tan z = (sin 2x + j sinh 2y) / (cos 2x + cosh 2y).

    The quotient form is used rather than sin z / cos z because it divides once by a real number that is never small unless both parts are: cosh 2y >= 1 keeps the divisor away from zero for any imaginary part at all.

    BigComplex::tanh

    fn BigComplex::tanh(self : BigComplex, context? : Context) -> BigComplex

    tanh z = (sinh 2x + j sin 2y) / (cosh 2x + cos 2y), the hyperbolic twin of the tangent's quotient form: cosh 2x >= 1 keeps the divisor away from zero.

    BigComplex::to_real

    fn BigComplex::to_real(self : BigComplex, context? : Context) -> BigFloat raise Refused

    The way back, for a caller who knows the imaginary part is zero.

    Refuses rather than dropping a part that is not zero: 2 + 3j is not a real number, and a to_real that answered 2 would be the kind of quiet answer this library does not give.

    BigComplex::to_string

    fn BigComplex::to_string(self : BigComplex) -> String

    BigFloat

    pub struct BigFloat {
    kind : Kind
    mantissa :
    BigInt

    exponent : Int
    precision : Int
    }

    A real number carried to a precision of its own.

    The value is mantissa * 2^exponent while it is finite, with the significand an integer of no more bits than precision says. The exponent is binary because the arithmetic underneath is binary: multiplying by ten would round where multiplying by two does not.

    Every operation rounds its result to a width — the wider of its operands, or the one a Context names — and keeps that width on the answer, so the next operation inherits it without the caller having to repeat it.
    impl Add for BigFloat
    impl Compare for BigFloat
    impl Default for BigFloat
    impl Div for BigFloat
    impl Eq for BigFloat
    impl Mul for BigFloat
    impl Neg for BigFloat
    impl Show for BigFloat
    impl Sub for BigFloat

    BigFloat::abs

    fn BigFloat::abs(self : BigFloat) -> BigFloat

    The absolute value, at the same width.

    BigFloat::acos

    fn BigFloat::acos(self : BigFloat, context? : Context) -> BigFloat

    The arccosine, as a quarter turn less the arcsine.

    BigFloat::acosh

    fn BigFloat::acosh(self : BigFloat, context? : Context) -> BigFloat

    The inverse hyperbolic cosine, as asinh(sqrt(x^2 - 1)), which is real from one upwards and holds its digits there where ln(x + sqrt(x^2 - 1)) would not.

    BigFloat::add

    fn BigFloat::add(self : BigFloat, other : BigFloat) -> BigFloat

    BigFloat::asin

    fn BigFloat::asin(self : BigFloat, context? : Context) -> BigFloat

    The arcsine, through atan(x / sqrt(1 - x^2)), which is real only inside the unit interval.

    BigFloat::asinh

    fn BigFloat::asinh(self : BigFloat, context? : Context) -> BigFloat

    The inverse hyperbolic sine, as ln(1 + u) with u = x + x^2 / (sqrt(1 + x^2) + 1).

    The 1 + that would swallow a small argument never gets formed: the rational form of the square root keeps the small part, and ln_one_plus is the logarithm that can take it.

    BigFloat::atan

    fn BigFloat::atan(self : BigFloat, context? : Context) -> BigFloat

    The arctangent, at the context's width and direction.

    BigFloat::atanh

    fn BigFloat::atanh(self : BigFloat, context? : Context) -> BigFloat

    The inverse hyperbolic tangent, as half the log of (1 + x) / (1 - x).

    At one the answer is unbounded and the two infinities are the answer; past it there is no real value.

    BigFloat::compare

    fn BigFloat::compare(self : BigFloat, other : BigFloat) -> Int

    BigFloat::cos

    fn BigFloat::cos(self : BigFloat, context? : Context) -> BigFloat

    The cosine, at the context's width and direction.

    BigFloat::cosh

    fn BigFloat::cosh(self : BigFloat, context? : Context) -> BigFloat

    The hyperbolic cosine, at the context's width and direction.

    BigFloat::default

    fn BigFloat::default() -> BigFloat

    BigFloat::div

    fn BigFloat::div(self : BigFloat, other : BigFloat) -> BigFloat

    BigFloat::divide

    fn BigFloat::divide(self : BigFloat, other : BigFloat, context? : Context) -> BigFloat raise Refused

    The quotient, raising ZeroDivision instead of answering an infinity.

    The operator cannot raise, so it answers ±inf and nan the way IEEE 754 does; a caller who would rather be told calls this.

    BigFloat::e

    fn BigFloat::e(context? : Context) -> BigFloat

    e at the width and rounding of context, as exp(1) — not a table.

    BigFloat::equal

    fn BigFloat::equal(self : BigFloat, other : BigFloat) -> Bool

    BigFloat::exp

    fn BigFloat::exp(self : BigFloat, context? : Context) -> BigFloat

    The exponential at the context's width and direction.

    BigFloat::expm1

    fn BigFloat::expm1(self : BigFloat, context? : Context) -> BigFloat

    e^x - 1 at the context's width and direction.

    BigFloat::infinity

    fn BigFloat::infinity() -> BigFloat

    Past every number the exponent can name, above zero.

    BigFloat::is_finite

    fn BigFloat::is_finite(self : BigFloat) -> Bool

    Whether the value is a number.

    BigFloat::is_infinite

    fn BigFloat::is_infinite(self : BigFloat) -> Bool

    Whether the value is past every number the exponent can name.

    BigFloat::is_nan

    fn BigFloat::is_nan(self : BigFloat) -> Bool

    Whether the value is the answer to a question with none.

    BigFloat::is_zero

    fn BigFloat::is_zero(self : BigFloat) -> Bool

    Whether the value is zero. A zero is a number; an infinity is not one.

    BigFloat::kind

    fn BigFloat::kind(self : BigFloat) -> Kind

    The kind of value this is.

    BigFloat::ln

    fn BigFloat::ln(self : BigFloat, context? : Context) -> BigFloat

    The logarithm at the context's width and direction.

    BigFloat::ln2

    fn BigFloat::ln2(context? : Context) -> BigFloat

    ln(2) at the width and rounding of context.

    BigFloat::log1p

    fn BigFloat::log1p(self : BigFloat, context? : Context) -> BigFloat

    ln(1 + x) at the context's width and direction.

    BigFloat::mul

    fn BigFloat::mul(self : BigFloat, other : BigFloat) -> BigFloat

    BigFloat::nan

    fn BigFloat::nan() -> BigFloat

    Not a number.

    BigFloat::neg

    fn BigFloat::neg(self : BigFloat) -> BigFloat

    BigFloat::negative_infinity

    fn BigFloat::negative_infinity() -> BigFloat

    The same, below zero.

    BigFloat::not_equal

    fn BigFloat::not_equal(x : BigFloat, y : BigFloat) -> Bool

    BigFloat::of_bigint

    fn BigFloat::of_bigint(value :
    BigInt
    , context? : Context) -> BigFloat

    An arbitrary-precision integer as a value, rounded when the context is narrower than the integer.

    BigFloat::of_double

    fn BigFloat::of_double(value : Double) -> BigFloat

    A double as a value, exactly.

    Every finite double is a binary fraction, so this is not a round trip through text and loses nothing: the significand and the exponent of the double are the significand and the exponent of the BigFloat, at 53 bits.

    BigFloat::of_fixed

    fn BigFloat::of_fixed(value : Fixed, context? : Context) -> BigFloat

    A fixed-point value as a value, exactly when the width allows and rounded half to even when it does not.

    BigFloat::of_int

    fn BigFloat::of_int(value : Int, context? : Context) -> BigFloat

    An integer as a value, rounded when the context is narrower than the integer.

    BigFloat::one

    fn BigFloat::one(context? : Context) -> BigFloat

    The number one.

    BigFloat::op_ge

    fn BigFloat::op_ge(x : BigFloat, y : BigFloat) -> Bool

    BigFloat::op_gt

    fn BigFloat::op_gt(x : BigFloat, y : BigFloat) -> Bool

    BigFloat::op_le

    fn BigFloat::op_le(x : BigFloat, y : BigFloat) -> Bool

    BigFloat::op_lt

    fn BigFloat::op_lt(x : BigFloat, y : BigFloat) -> Bool

    BigFloat::output

    fn BigFloat::output(self : BigFloat, logger : &Logger) -> Unit

    BigFloat::parse

    fn BigFloat::parse(text : StringView, context? : Context) -> BigFloat raise Refused

    A decimal from outside, rounded once at the end to context's width and direction.

    Reads what float() reads: an optional sign, digits with an optional point and exponent, a single underscore between digits, surrounding whitespace, and inf, infinity and nan in any case. A decimal exponent past a hundred thousand is refused rather than answered with a zero or an infinity that was not written.

    BigFloat::pi

    fn BigFloat::pi(context? : Context) -> BigFloat

    pi at the width and rounding of context.

    BigFloat::pow

    fn BigFloat::pow(self : BigFloat, exponent : BigFloat, context? : Context) -> BigFloat

    base raised to exponent, at the context's width and direction.

    A negative base with a fractional exponent has no real value and answers NaN, as does anything that would need the logarithm of a negative number.

    BigFloat::precision

    fn BigFloat::precision(self : BigFloat) -> Int

    The width the value was rounded to, in bits.

    BigFloat::round

    fn BigFloat::round(self : BigFloat, context? : Context) -> BigFloat

    The value at another width and rounding, which is what Context is for at the point where a caller wants to fix a width once and pass values through it.

    BigFloat::sign

    fn BigFloat::sign(self : BigFloat) -> Int

    -1, 0 or 1: the sign of the value, and 0 where there is no sign to give, as for a NaN.

    BigFloat::sin

    fn BigFloat::sin(self : BigFloat, context? : Context) -> BigFloat

    The sine, at the context's width and direction.

    BigFloat::sinh

    fn BigFloat::sinh(self : BigFloat, context? : Context) -> BigFloat

    The hyperbolic sine, at the context's width and direction.

    BigFloat::sqrt

    fn BigFloat::sqrt(self : BigFloat, context? : Context) -> BigFloat

    The square root, rounded at the context's width and direction.

    BigFloat::sub

    fn BigFloat::sub(self : BigFloat, other : BigFloat) -> BigFloat

    BigFloat::tan

    fn BigFloat::tan(self : BigFloat, context? : Context) -> BigFloat

    The tangent, as the sine over the cosine.

    A remainder at a quarter turn gives a cosine of zero and so an infinity, which is what the tangent of a quarter turn is.

    BigFloat::tanh

    fn BigFloat::tanh(self : BigFloat, context? : Context) -> BigFloat

    The hyperbolic tangent, as the sine over the cosine.

    BigFloat::to_bigint

    fn BigFloat::to_bigint(self : BigFloat, rounding? : Rounding) ->
    BigInt
    raise Refused

    The value rounded to an integer, Nearest being ties to even.

    An infinity and a NaN have no integer, and saying so is the point: a caller handed zero instead would not know it had not been given one.

    BigFloat::to_complex

    fn BigFloat::to_complex(self : BigFloat) -> BigComplex

    The promotion: the same value with an imaginary part of zero at the same width.

    Exact — a real number is a complex number already, and nothing is rounded by saying so. This is how a caller reaches the principal square root of a negative, or the logarithm of one:

    let c = @moonnum.Context::new(200)
    (-@moonnum.BigFloat::one(context=c)).to_complex().sqrt(context=c) // 0 + 1j

    BigFloat::to_decimal

    fn BigFloat::to_decimal(self : BigFloat, places : Int) -> String

    This is the spelling for a table or a printed constant, so the count is a promise rather than a maximum: to_decimal(2) of one half is 0.50.

    BigFloat::to_double

    fn BigFloat::to_double(self : BigFloat) -> Double

    The nearest double, ties to even.

    A value above the largest double is an infinity and one below the smallest is a zero, which is what the host does with the same value; inside that range the answer is the correctly rounded double of the exact value.

    BigFloat::to_fixed

    fn BigFloat::to_fixed(self : BigFloat, bits : Int) -> Fixed raise Refused

    The value as a fixed-point number with bits fractional bits, rounded half to even on the exact value.

    The width is the caller's because a Fixed has no precision of its own: the count of fractional bits decides how finely it can sit, and a value far from one needs more of them for the same count of digits.

    BigFloat::to_significant

    fn BigFloat::to_significant(self : BigFloat, digits : Int) -> String

    The value with digits significant decimal digits, trailing zeros dropped and the point placed where the plain form keeps it.

    BigFloat::to_string

    fn BigFloat::to_string(self : BigFloat) -> String

    BigFloat::zero

    fn BigFloat::zero(context? : Context) -> BigFloat

    The number zero.

    Complex

    pub(all) struct Complex {
    re : Double
    im : Double
    }

    A complex number: z.re + z.im * j.

    Adds, subtracts, multiplies, negates and compares with ==; division is Complex::divide because it can refuse a zero divisor.
    impl Add for Complex
    impl Default for Complex
    impl Eq for Complex
    impl Mul for Complex
    impl Neg for Complex
    impl Show for Complex
    impl Sub for Complex

    Complex::abs

    fn Complex::abs(self : Complex) -> Double

    abs(z): the Euclidean norm, infinity when either part is infinite.

    Complex::add

    fn Complex::add(self : Complex, other : Complex) -> Complex

    Complex::conjugate

    fn Complex::conjugate(self : Complex) -> Complex

    z.conjugate().

    Complex::default

    fn Complex::default() -> Complex

    Complex::divide

    fn Complex::divide(self : Complex, other : Complex) -> Complex raise Refused

    self / other.

    A function rather than an operator, for the same reason as Fraction::divide: division by zero has to be reported, and Div cannot.

    Complex::equal

    fn Complex::equal(self : Complex, other : Complex) -> Bool

    Complex::format

    fn Complex::format(self : Complex, spec_text : StringView) -> String raise Refused

    Format a complex number: the real part with the specifier's sign, the imaginary part forced positive, then j, in parentheses unless the real part is a positive zero.

    Complex::j

    fn Complex::j() -> Complex

    The imaginary unit.

    Complex::mul

    fn Complex::mul(self : Complex, other : Complex) -> Complex

    Complex::neg

    fn Complex::neg(self : Complex) -> Complex

    Complex::new

    fn Complex::new(re : Double, im : Double) -> Complex

    Complex(re, im).

    Complex::not_equal

    fn Complex::not_equal(x : Complex, y : Complex) -> Bool

    Complex::output

    fn Complex::output(self : Complex, logger : &Logger) -> Unit

    Complex::pow

    fn Complex::pow(self : Complex, w : Complex) -> Complex raise Refused

    z ** w, including Python's special cases.

    An exponent that is a small integer is applied by repeated squaring, as CPython does; anything else goes through the polar form, which is why (1+1j) ** 2 is exactly 2j and (1+1j) ** 2.0 is not.

    Complex::sub

    fn Complex::sub(self : Complex, other : Complex) -> Complex

    Complex::to_string

    fn Complex::to_string(self : Complex) -> String

    Context

    pub struct Context {
    precision : Int
    rounding : Rounding
    }

    A width in bits and the direction a result that does not fit is rounded in.

    The two travel together because a rounding mode without a width has nothing to round, and a width without a mode leaves the last bit to chance.

    Context::add

    fn Context::add(self : Context, a : BigFloat, b : BigFloat) -> BigFloat

    The sum of a and b at this width and rounding.

    Context::add_complex

    fn Context::add_complex(self : Context, a : BigComplex, b : BigComplex) -> BigComplex

    z + w at the context's width and direction — the complex twin of Context::add, which is the only way to ask for a width other than the wider of the two operands.

    Context::div

    fn Context::div(self : Context, a : BigFloat, b : BigFloat) -> BigFloat

    The quotient of a and b at this width and rounding, answering ±inf and nan where that is the answer.

    Context::divide

    fn Context::divide(self : Context, a : BigFloat, b : BigFloat) -> BigFloat raise Refused

    The quotient of a and b, raising ZeroDivision for a zero divisor.

    Context::divide_complex

    fn Context::divide_complex(self : Context, a : BigComplex, b : BigComplex) -> BigComplex raise Refused

    z / w at the context's width, refusing a zero divisor as divide does.

    Context::mul

    fn Context::mul(self : Context, a : BigFloat, b : BigFloat) -> BigFloat

    The product of a and b at this width and rounding.

    Context::mul_complex

    fn Context::mul_complex(self : Context, a : BigComplex, b : BigComplex) -> BigComplex

    z * w at the context's width.

    Context::new

    fn Context::new(precision : Int, rounding? : Rounding) -> Context

    A context of precision bits, rounding to nearest even unless told otherwise.

    A width below one is raised to one: a significand of no bits holds nothing but zero, and silently answering zero for every operation is worse than answering the one bit that was asked for.

    Context::sub

    fn Context::sub(self : Context, a : BigFloat, b : BigFloat) -> BigFloat

    The difference of a and b at this width and rounding.

    Context::sub_complex

    fn Context::sub_complex(self : Context, a : BigComplex, b : BigComplex) -> BigComplex

    z - w at the context's width.

    Fixed

    pub struct Fixed {
    mantissa :
    BigInt

    bits : Int
    }

    A real number carried as mantissa / 2^bits.

    bits is the number of fractional bits, so the value has about bits * 0.301 decimal digits after the point. An operation keeps the left operand's width and brings the right one to it, so two widths give the answer the left width can hold rather than a wrong one.

    A value outside an operation's domain, such as the square root of a negative number, stops the program with the reason, as a division of integers by zero does: these operations are written with + and * and cannot raise. Text from outside goes through parse_fixed, which does.
    impl Add for Fixed
    impl Compare for Fixed
    impl Div for Fixed
    impl Eq for Fixed
    impl Mul for Fixed
    impl Neg for Fixed
    impl Show for Fixed
    impl Sub for Fixed

    Fixed::abs

    fn Fixed::abs(self : Fixed) -> Fixed

    The absolute value.

    Fixed::add

    fn Fixed::add(self : Fixed, other : Fixed) -> Fixed

    Fixed::approx

    fn Fixed::approx(self : Fixed, other : Fixed, tolerance : Fixed) -> Bool

    Whether the two are within tolerance of each other.

    Fixed::at

    fn Fixed::at(self : Fixed, bits : Int) -> Fixed

    The same value at another width: exact when it widens, truncated when it narrows.

    Fixed::atan

    fn Fixed::atan(self : Fixed) -> Fixed

    The arctangent, by halving the angle until the series converges and doubling the result back. atan x = 2 atan (x / (1 + sqrt(1 + x^2))) holds for every x, and each halving quarters the argument, so the Taylor series is reached after a handful of steps from anywhere.

    Fixed::bits_for_digits

    fn Fixed::bits_for_digits(digits : Int) -> Int

    The fractional bits for a requested count of decimal digits, with guard bits left for the truncation each operation drops.

    Fixed::compare

    fn Fixed::compare(self : Fixed, other : Fixed) -> Int

    Fixed::cos

    fn Fixed::cos(self : Fixed) -> Fixed

    The cosine, by the same reduction and the Taylor series that starts at one.

    Fixed::digits_for_bits

    fn Fixed::digits_for_bits(bits : Int) -> Int

    The decimal digits a width can represent, guard bits included.

    Fixed::div

    fn Fixed::div(self : Fixed, other : Fixed) -> Fixed

    Fixed::equal

    fn Fixed::equal(self : Fixed, other : Fixed) -> Bool

    Fixed::exp

    fn Fixed::exp(self : Fixed) -> Fixed

    e^x, by range reduction to -ln(2)/2 .. ln(2)/2 and a Taylor series.

    Fixed::is_zero

    fn Fixed::is_zero(self : Fixed) -> Bool

    Whether the value is exactly zero.

    Fixed::ln

    fn Fixed::ln(self : Fixed) -> Fixed

    The natural logarithm, by ln(m) + k ln(2) with m in 1..2 and the atanh series for ln(m).

    Fixed::ln2

    fn Fixed::ln2(bits : Int) -> Fixed

    ln(2) at the given width, 2 atanh(1/3) past the width of the constant.

    Fixed::mul

    fn Fixed::mul(self : Fixed, other : Fixed) -> Fixed

    Fixed::neg

    fn Fixed::neg(self : Fixed) -> Fixed

    Fixed::not_equal

    fn Fixed::not_equal(x : Fixed, y : Fixed) -> Bool

    Fixed::of_decimal

    fn Fixed::of_decimal(text : String, bits : Int) -> Fixed

    A decimal literal at the given width: "0.5772156649", "-3.14", "1e-40".

    This is how a constant that is known to more digits than a double holds gets into a computation without a caller having to hand-count the places. The digits are read as an integer and divided by the matching power of ten once, so the only rounding is that single division. It is for constants a program carries; text from outside goes through parse_fixed.

    Fixed::of_int

    fn Fixed::of_int(value : Int, bits : Int) -> Fixed

    An integer at the given width.

    Fixed::of_scaled

    fn Fixed::of_scaled(integer : String, places : Int, bits : Int) -> Fixed

    integer / 10^places at the given width: how a decimal constant such as pi is seeded without a parser.

    Fixed::one

    fn Fixed::one(bits : Int) -> Fixed

    One at the given width.

    Fixed::op_ge

    fn Fixed::op_ge(x : Fixed, y : Fixed) -> Bool

    Fixed::op_gt

    fn Fixed::op_gt(x : Fixed, y : Fixed) -> Bool

    Fixed::op_le

    fn Fixed::op_le(x : Fixed, y : Fixed) -> Bool

    Fixed::op_lt

    fn Fixed::op_lt(x : Fixed, y : Fixed) -> Bool

    Fixed::output

    fn Fixed::output(self : Fixed, logger : &Logger) -> Unit

    Fixed::pi

    fn Fixed::pi(bits : Int) -> Fixed

    Pi at the given width, Machin's formula past the width of the constant.

    Fixed::pow

    fn Fixed::pow(self : Fixed, exponent : Fixed) -> Fixed

    x^y, through exp(y ln x). The base must be positive: a fixed-point value has no branch for a negative base and a fractional exponent.

    Fixed::sin

    fn Fixed::sin(self : Fixed) -> Fixed

    The sine, by range reduction to -pi .. pi and the Taylor series.

    Fixed::sqrt

    fn Fixed::sqrt(self : Fixed) -> Fixed

    The square root, rounded down to the width.

    Fixed::sub

    fn Fixed::sub(self : Fixed, other : Fixed) -> Fixed

    Fixed::to_decimal

    fn Fixed::to_decimal(self : Fixed, places : Int) -> String

    The value in decimal with places digits after the point, rounded half away from zero.

    Fixed::to_double

    fn Fixed::to_double(self : Fixed) -> Double

    The value as a double, to the precision a double holds.

    Fixed::to_string

    fn Fixed::to_string(self : Fixed) -> String

    Fixed::zero

    fn Fixed::zero(bits : Int) -> Fixed

    Zero at the given width.

    Fraction

    A rational number. den is always positive and gcd(num, den) is always 1, so num and den can be read directly.

    Adds, subtracts, multiplies, negates, compares with == and an ordering; division is Fraction::divide because it can refuse a zero divisor.
    impl Add for Fraction
    impl Compare for Fraction
    impl Default for Fraction
    impl Eq for Fraction
    impl Mul for Fraction
    impl Neg for Fraction
    impl Show for Fraction
    impl Sub for Fraction

    Fraction::abs

    fn Fraction::abs(self : Fraction) -> Fraction

    The same value without its sign.

    Fraction::add

    fn Fraction::add(self : Fraction, other : Fraction) -> Fraction

    Fraction::ceil_big

    math.ceil, as an integer.

    Fraction::compare

    fn Fraction::compare(self : Fraction, other : Fraction) -> Int

    Fraction::default

    fn Fraction::default() -> Fraction

    Fraction::denominator

    The denominator, always positive.

    Fraction::divide

    fn Fraction::divide(self : Fraction, other : Fraction) -> Fraction raise Refused

    self / other.

    Division is a function and not an operator here: MoonBit's Div trait cannot raise, and a fraction that silently divides by zero or panics would be worse than one that says ZeroDivision.

    Fraction::equal

    fn Fraction::equal(self : Fraction, other : Fraction) -> Bool

    Fraction::floor_big

    math.floor, as an integer.

    Fraction::floor_divide_big

    fn Fraction::floor_divide_big(self : Fraction, other : Fraction) ->
    BigInt
    raise Refused

    self // other as an integer: Python's floor division of two fractions.

    Fraction::format

    fn Fraction::format(self : Fraction, spec_text : StringView) -> String raise Refused

    Format a fraction. Without a presentation type it is a ratio, with a digit grouping separator allowed in both halves; with a float type it is the exact rational rounded to the requested digits.

    Fraction::is_integer

    fn Fraction::is_integer(self : Fraction) -> Bool

    Whether the value is a whole number.

    Fraction::limit_denominator

    fn Fraction::limit_denominator(self : Fraction, max~ :
    BigInt
    ) -> Fraction raise Refused

    The closest fraction whose denominator is at most max.

    Fraction::modulo

    fn Fraction::modulo(self : Fraction, other : Fraction) -> Fraction raise Refused

    self % other: the remainder that takes the sign of the divisor.

    Fraction::mul

    fn Fraction::mul(self : Fraction, other : Fraction) -> Fraction

    Fraction::neg

    fn Fraction::neg(self : Fraction) -> Fraction

    Fraction::not_equal

    fn Fraction::not_equal(x : Fraction, y : Fraction) -> Bool

    Fraction::numerator

    The numerator, with the sign.

    Fraction::of_float

    fn Fraction::of_float(d : Double) -> Fraction raise Refused

    The exact value of a float, as a fraction. 0.1 is not 1/10 here; it is 3602879701896397/36028797018963968, which is what the double holds.

    Fraction::of_int

    The integer n as a fraction.

    Fraction::op_ge

    fn Fraction::op_ge(x : Fraction, y : Fraction) -> Bool

    Fraction::op_gt

    fn Fraction::op_gt(x : Fraction, y : Fraction) -> Bool

    Fraction::op_le

    fn Fraction::op_le(x : Fraction, y : Fraction) -> Bool

    Fraction::op_lt

    fn Fraction::op_lt(x : Fraction, y : Fraction) -> Bool

    Fraction::output

    fn Fraction::output(self : Fraction, logger : &Logger) -> Unit

    Fraction::pow

    self ** exp for an integer exponent.

    The exponent is applied to the numerator and the denominator separately, so (2/3) ** 100 is one exact ratio and not a double that nearly is. A negative exponent reciprocates, which is why 0 ** -1 is ZeroDivision and 0 ** 0 is 1, as in Python.

    Fraction::reciprocal

    fn Fraction::reciprocal(self : Fraction) -> Fraction raise Refused

    1/self.

    Fraction::round

    fn Fraction::round(self : Fraction, ndigits~ : Int) -> Fraction

    round(self, ndigits): round to ndigits decimal places, ties to even.

    Fraction::round_big

    round(self): the nearest integer, ties to even.

    Fraction::sub

    fn Fraction::sub(self : Fraction, other : Fraction) -> Fraction

    Fraction::to_double

    fn Fraction::to_double(self : Fraction) -> Double raise Refused

    The nearest double, or Overflow when the value does not fit.

    Fraction::to_string

    fn Fraction::to_string(self : Fraction) -> String

    Kind

    pub(all) enum Kind {
    Finite
    PositiveInfinity
    NegativeInfinity
    NotANumber
    } derive(Eq)

    What a BigFloat is.

    A caller who matches on this has seen every value the type can hold, which is the reason it is one enum and not three predicates.

    Kind::equal

    fn Kind::equal(Kind, Kind) -> Bool

    Kind::not_equal

    fn Kind::not_equal(x : Kind, y : Kind) -> Bool

    Number

    pub(all) enum Number {
    Int(
    BigInt
    )
    Float(Double)
    Fraction(Fraction)
    Complex(Complex)
    }

    A number of any kind, as the tower arranges them.

    Promotion goes Int → Fraction → Float → Complex. Comparison is exact across the tower: an integer is never rounded to a float to be compared with one.
    impl Add for Number
    impl Eq for Number
    impl Mul for Number
    impl Neg for Number
    impl Show for Number
    impl Sub for Number

    Number::add

    fn Number::add(self : Number, other : Number) -> Number

    Number::compare_numeric

    fn Number::compare_numeric(self : Number, other : Number) -> Int raise Refused

    Compare two real numbers, exactly.

    Raises Domain for a NaN operand and for a complex number with a non-zero imaginary part, which Python refuses to order.

    Number::divide

    fn Number::divide(self : Number, other : Number) -> Number raise Refused

    a / b, with Python's result kinds: two integers divide to a float, a fraction stays exact, and a complex number is complex.

    Number::equal

    fn Number::equal(self : Number, other : Number) -> Bool

    Number::equal_numeric

    fn Number::equal_numeric(self : Number, other : Number) -> Bool

    a == b, across the tower: 1 == 1.0 == Fraction(1) == 1 + 0j.

    Number::floor_mod

    fn Number::floor_mod(self : Number, other : Number) -> Number raise Refused

    a % b: the remainder that takes the sign of the divisor.

    Number::floordiv

    fn Number::floordiv(self : Number, other : Number) -> Number raise Refused

    a // b.

    Number::mul

    fn Number::mul(self : Number, other : Number) -> Number

    Number::neg

    fn Number::neg(self : Number) -> Number

    Number::not_equal

    fn Number::not_equal(x : Number, y : Number) -> Bool

    Number::output

    fn Number::output(self : Number, logger : &Logger) -> Unit

    Number::pow

    fn Number::pow(self : Number, exponent : Number) -> Number raise Refused

    a ** b.

    Number::sub

    fn Number::sub(self : Number, other : Number) -> Number

    Number::to_double

    fn Number::to_double(self : Number) -> Double raise Refused

    The value as a double, or Overflow when it is infinite or not real.

    Number::to_string

    fn Number::to_string(self : Number) -> String

    Rounding

    pub(all) enum Rounding {
    Nearest
    Floor
    Ceiling
    Down
    Up
    } derive(Eq)

    How a result that does not fit the width it is rounded to is rounded.

    The five are the reference's n, f, c, d and u. Nearest breaks a tie toward the even digit, so a sequence of roundings does not drift upward the way ties-away-from-zero does.
    impl Show for Rounding

    Rounding::equal

    fn Rounding::equal(Rounding, Rounding) -> Bool

    Rounding::not_equal

    fn Rounding::not_equal(x : Rounding, y : Rounding) -> Bool

    Rounding::output

    fn Rounding::output(self : Rounding, logger : &Logger) -> Unit

    Rounding::to_string

    fn Rounding::to_string(self : Rounding) -> String

    as_integer_ratio

    float.as_integer_ratio: the exact numerator and denominator of d.

    as_ratio

    fn as_ratio(d : Double) -> Fraction raise Refused

    d as an exact fraction.

    bit_length

    fn bit_length(n :
    BigInt
    ) -> Int

    The number of bits needed to represent n, sign excluded: int.bit_length.

    ceil_big

    fn ceil_big(d : Double) ->
    BigInt
    raise Refused

    math.ceil(d), as an integer.

    comb

    math.comb(n, k): the number of ways to choose k from n without repetition.

    context_default

    let context_default : Context

    What an operation uses when the caller names no context: 53 bits to nearest even, which is the width and the mode of a double. A BigFloat computed with it and a Double computed by the host agree to the bit, so the two can be compared without a tolerance.

    float_hex

    fn float_hex(d : Double) -> String

    The hexadecimal form of a double: float.hex.

    float_of_hex

    fn float_of_hex(text : StringView) -> Double raise Refused

    float.fromhex: the double a hexadecimal literal denotes.

    The 0x prefix is optional, the exponent is decimal and introduced by p, and the rounding is the same half-to-even as every other conversion here.

    floor_big

    fn floor_big(d : Double) ->
    BigInt
    raise Refused

    math.floor(d), as an integer.

    floor_mod

    a % b: the remainder that takes the sign of the divisor.

    floordiv

    a // b: the quotient rounded towards negative infinity.

    format

    fn format(value : Number, spec_text : StringView) -> String raise Refused

    format(value, spec), for any number.

    format_float

    fn format_float(d : Double, spec_text : StringView) -> String raise Refused

    Format a double the way Python's format() does.

    format_int

    fn format_int(n :
    BigInt
    , spec_text : StringView) -> String raise Refused

    Format an integer, including the float types Python allows on integers by converting them.

    isqrt

    math.isqrt(n): the floor of the square root.

    lcm

    The least common multiple, always non-negative; zero when either side is.

    of_bytes

    fn of_bytes(bytes : BytesView, big? : Bool, signed? : Bool) ->
    BigInt

    int.from_bytes: the integer held by bytes, big-endian unless big~ = false, two's complement when signed~ = true.

    parse

    fn parse(text : StringView) -> Number raise Refused

    parse(text): read a Python number literal and keep the kind it spelled.

    A / makes a fraction, a trailing j or i makes a complex number, a point or an exponent or inf/nan makes a float, and anything else is an integer in whatever base its prefix names.

    parse_complex

    fn parse_complex(text : StringView) -> Complex raise Refused

    complex(text): 1+2j, (1+2j), j, -j, 1e3j, and 3+5i.

    The i suffix is this library's addition; Python only reads j.

    parse_fixed

    fn parse_fixed(text : StringView, bits : Int) -> Fixed raise Refused

    A decimal literal from outside: an optional sign, digits with an optional point, and an optional exponent. Anything else is refused with where it stopped.

    parse_float

    fn parse_float(text : StringView) -> Double raise Refused

    float(text): Python's float literal syntax.

    Accepts inf, infinity and nan in any case with an optional sign, decimal forms with or without a fractional part or an exponent, single underscores between digits, and surrounding whitespace. Hexadecimal literals are not float syntax; float_of_hex reads those.

    parse_fraction

    fn parse_fraction(text : StringView) -> Fraction raise Refused

    Fraction(text): "3/4", "-1.25", "1e-3", "7".

    Whitespace is allowed around the sign, the slash and the ends; digits may be separated by single underscores. The decimal and exponent forms are read as exact powers of ten, never through a float.

    parse_int

    fn parse_int(text : StringView, base? : Int) ->
    BigInt
    raise Refused

    int(text, base): an integer in any base from 2 to 36, with Python's spelling rules.

    Surrounding whitespace is allowed, the sign is optional, digits may be separated by single underscores, and base = 0 means "read the prefix": 0x for hexadecimal, 0o for octal, 0b for binary, decimal otherwise — and, as in Python, leading zeros are then not allowed.

    perm

    math.perm(n, k): the number of ways to choose k from n in order.

    power

    pow(base, exp, modulus), and pow(base, exp) when modulus is absent.

    With a modulus and a negative exponent the result is the modular inverse raised to -exp, which is Python's behaviour since 3.8. Without a modulus a negative exponent has no integer answer and is refused.

    repr_complex

    fn repr_complex(z : Complex) -> String

    repr(z): (1+2j), 2j, (-0-1j), (nan+infj).

    repr_float

    fn repr_float(d : Double) -> String

    repr(float): the shortest string that reads back as the same double.

    repr_fraction

    fn repr_fraction(f : Fraction) -> String

    repr(Fraction(3, 4)).

    round_big

    fn round_big(d : Double) ->
    BigInt
    raise Refused

    round(d): the nearest integer, ties to even.

    round_float

    fn round_float(d : Double, ndigits~ : Int) -> Double

    round(d, ndigits): round to ndigits decimal places, ties to even, on the exact value of d.

    to_bytes

    fn to_bytes(n :
    BigInt
    , length~ : Int, big? : Bool, signed? : Bool) -> Bytes raise Refused

    int.to_bytes: length bytes holding n, big-endian unless big~ = false.

    A signed result is two's complement; an unsigned one refuses negatives.

    trunc_big

    fn trunc_big(d : Double) ->
    BigInt
    raise Refused

    math.trunc(d), as an integer.