moonnum.
ReferenceEvery public item

API reference

Signatures as the compiler sees them, prose as written beside the code. Generated from the module interface, so nothing here is aspirational.

Integers

Arbitrary-precision integers: core's BigInt, plus the operations and spellings a numeric program needs.

pub fn bit_length(@bigint.BigInt) -> Int32

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

pub fn comb(@bigint.BigInt, @bigint.BigInt) -> @bigint.BigInt raise Refused

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

pub fn divmod(@bigint.BigInt, @bigint.BigInt) -> (@bigint.BigInt, @bigint.BigInt) raise Refused

divmod(a, b): the floor quotient and the matching remainder.

pub fn factorial(@bigint.BigInt) -> @bigint.BigInt raise Refused

math.factorial(n).

pub fn floor_mod(@bigint.BigInt, @bigint.BigInt) -> @bigint.BigInt raise Refused

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

pub fn floordiv(@bigint.BigInt, @bigint.BigInt) -> @bigint.BigInt raise Refused

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

pub fn gcd(@bigint.BigInt, @bigint.BigInt) -> @bigint.BigInt

The greatest common divisor, always non-negative.

pub fn isqrt(@bigint.BigInt) -> @bigint.BigInt raise Refused

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

pub fn lcm(@bigint.BigInt, @bigint.BigInt) -> @bigint.BigInt

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

pub fn of_bytes(BytesView, big? : Bool, signed? : Bool) -> @bigint.BigInt

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

pub fn parse_int(StringView, base? : Int32) -> @bigint.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.

pub fn perm(@bigint.BigInt, @bigint.BigInt) -> @bigint.BigInt raise Refused

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

pub fn power(@bigint.BigInt, @bigint.BigInt, modulus? : @bigint.BigInt) -> @bigint.BigInt raise Refused

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.

pub fn to_bytes(@bigint.BigInt, length~ : Int32, 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.

Floats

Reading, writing and rounding IEEE-754 doubles.

pub fn as_integer_ratio(Double) -> (@bigint.BigInt, @bigint.BigInt) raise Refused

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

pub fn as_ratio(Double) -> Fraction raise Refused

d as an exact fraction.

pub fn ceil_big(Double) -> @bigint.BigInt raise Refused

math.ceil(d), as an integer.

pub fn float_hex(Double) -> String

The hexadecimal form of a double: float.hex.

pub fn float_of_hex(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.

pub fn floor_big(Double) -> @bigint.BigInt raise Refused

math.floor(d), as an integer.

pub fn parse_float(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.

pub fn repr_float(Double) -> String

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

pub fn round_big(Double) -> @bigint.BigInt raise Refused

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

pub fn round_float(Double, ndigits~ : Int32) -> Double

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

pub fn trunc_big(Double) -> @bigint.BigInt raise Refused

math.trunc(d), as an integer.

Complex numbers

Complex, its arithmetic, and its repr.

pub fn parse_complex(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.

pub fn repr_complex(Complex) -> String

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

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.

Implements Add (+) · Default (default()) · Eq (== and !=) · Mul (*) · Neg (unary -) · Show (to_string()) · Sub (-) — the methods they promote are public on Complex.

pub fn Complex::abs(Self) -> Double

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

pub fn Complex::conjugate(Self) -> Self

z.conjugate().

pub fn Complex::divide(Self, Self) -> Self 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.

pub fn Complex::format(Self, 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.

pub fn Complex::j() -> Self

The imaginary unit.

pub fn Complex::new(Double, Double) -> Self

Complex(re, im).

pub fn Complex::pow(Self, Self) -> Self 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.

Fixed point

A real at a width the caller picks, with the transcendentals a width is for.

pub fn parse_fixed(StringView, Int32) -> 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.

pub struct Fixed { mantissa : @bigint.BigInt bits : Int32 }

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.

Implements Add (+) · Compare (<, <=, >, >=) · Div (/) · Eq (== and !=) · Mul (*) · Neg (unary -) · Show (to_string()) · Sub (-) — the methods they promote are public on Fixed.

pub fn Fixed::abs(Self) -> Self

The absolute value.

pub fn Fixed::approx(Self, Self, Self) -> Bool

Whether the two are within tolerance of each other.

pub fn Fixed::at(Self, Int32) -> Self

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

pub fn Fixed::atan(Self) -> Self

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.

pub fn Fixed::bits_for_digits(Int32) -> Int32

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

pub fn Fixed::cos(Self) -> Self

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

pub fn Fixed::digits_for_bits(Int32) -> Int32

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

pub fn Fixed::div(Self, Self) -> Self

Truncated to the left width. A zero divisor stops the program, as it does for the integers underneath.

pub fn Fixed::exp(Self) -> Self

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

pub fn Fixed::is_zero(Self) -> Bool

Whether the value is exactly zero.

pub fn Fixed::ln(Self) -> Self

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

pub fn Fixed::ln2(Int32) -> Self

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

pub fn Fixed::of_decimal(String, Int32) -> Self

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.

pub fn Fixed::of_int(Int32, Int32) -> Self

An integer at the given width.

pub fn Fixed::of_scaled(String, Int32, Int32) -> Self

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

pub fn Fixed::one(Int32) -> Self

One at the given width.

pub fn Fixed::pi(Int32) -> Self

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

pub fn Fixed::pow(Self, Self) -> Self

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.

pub fn Fixed::sin(Self) -> Self

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

pub fn Fixed::sqrt(Self) -> Self

The square root, rounded down to the width.

pub fn Fixed::to_decimal(Self, Int32) -> String

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

pub fn Fixed::to_double(Self) -> Double

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

pub fn Fixed::zero(Int32) -> Self

Zero at the given width.

Binary floats

A real carried to a width the caller picks: the significand as wide as it needs, an exponent of its own, and a direction for the bits that do not fit.

pub struct BigFloat { kind : Kind mantissa : @bigint.BigInt exponent : Int32 precision : Int32 }

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.

Implements Add (+) · Compare (<, <=, >, >=) · Default (default()) · Div (/) · Eq (== and !=) · Mul (*) · Neg (unary -) · Show (to_string()) · Sub (-) — the methods they promote are public on BigFloat.

pub fn BigFloat::abs(Self) -> Self

The absolute value, at the same width.

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

The arccosine, as a quarter turn less the arcsine.

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

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.

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

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

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

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.

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

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

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

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.

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

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

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

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

pub fn BigFloat::div(Self, Self) -> Self

The quotient, answering ±inf and nan where the divisor is zero: the operator cannot raise, so it says what the standard says.

pub fn BigFloat::divide(Self, Self, context? : Context) -> Self 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.

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

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

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

The exponential at the context's width and direction.

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

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

pub fn BigFloat::infinity() -> Self

Past every number the exponent can name, above zero.

pub fn BigFloat::is_finite(Self) -> Bool

Whether the value is a number.

pub fn BigFloat::is_infinite(Self) -> Bool

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

pub fn BigFloat::is_nan(Self) -> Bool

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

pub fn BigFloat::is_zero(Self) -> Bool

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

pub fn BigFloat::kind(Self) -> Kind

The kind of value this is.

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

The logarithm at the context's width and direction.

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

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

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

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

pub fn BigFloat::nan() -> Self

Not a number.

pub fn BigFloat::negative_infinity() -> Self

The same, below zero.

pub fn BigFloat::of_bigint(@bigint.BigInt, context? : Context) -> Self

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

pub fn BigFloat::of_double(Double) -> Self

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.

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

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

pub fn BigFloat::of_int(Int32, context? : Context) -> Self

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

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

The number one.

pub fn BigFloat::parse(StringView, context? : Context) -> Self 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.

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

pi at the width and rounding of context.

pub fn BigFloat::pow(Self, Self, context? : Context) -> Self

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.

pub fn BigFloat::precision(Self) -> Int32

The width the value was rounded to, in bits.

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

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.

pub fn BigFloat::sign(Self) -> Int32

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

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

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

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

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

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

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

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

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.

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

The hyperbolic tangent, as the sine over the cosine.

pub fn BigFloat::to_bigint(Self, rounding? : Rounding) -> @bigint.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.

pub fn BigFloat::to_complex(Self) -> 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:

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

pub fn BigFloat::to_decimal(Self, Int32) -> 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.

pub fn BigFloat::to_double(Self) -> 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.

pub fn BigFloat::to_fixed(Self, Int32) -> 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.

pub fn BigFloat::to_significant(Self, Int32) -> String

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

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

The number zero.

pub struct Context { precision : Int32 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.

pub fn Context::add_complex(Self, BigComplex, 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.

pub fn Context::div(Self, BigFloat, BigFloat) -> BigFloat

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

pub fn Context::divide(Self, BigFloat, BigFloat) -> BigFloat raise Refused

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

pub fn Context::divide_complex(Self, BigComplex, BigComplex) -> BigComplex raise Refused

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

pub fn Context::mul_complex(Self, BigComplex, BigComplex) -> BigComplex

z * w at the context's width.

pub fn Context::new(Int32, rounding? : Rounding) -> Self

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.

pub fn Context::sub_complex(Self, BigComplex, BigComplex) -> BigComplex

z - w at the context's width.

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

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.

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

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.

Implements Show (to_string()) — the method it promotes is public on Rounding.

Complex numbers at any width

The second type the real functions needed: two BigFloat parts, the principal branches, and a promotion that a caller writes out.

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.

Implements Add (+) · Default (default()) · Eq (== and !=) · Mul (*) · Neg (unary -) · Show (to_string()) · Sub (-) — the methods they promote are public on BigComplex.

pub fn BigComplex::abs(Self, 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.

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

acos z at the context's width and direction.

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

acosh z at the context's width and direction.

pub fn BigComplex::arg(Self, 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.

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

asin z at the context's width and direction.

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

asinh z at the context's width and direction.

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

atan z at the context's width and direction.

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

atanh z at the context's width and direction.

pub fn BigComplex::conjugate(Self) -> Self

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

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

cos z at the context's width and direction.

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

cosh z at the context's width and direction.

pub fn BigComplex::divide(Self, Self, context? : Context) -> Self 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.

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

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

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

The imaginary unit at a width.

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

ln z at the context's width and direction.

pub fn BigComplex::new(BigFloat, BigFloat) -> Self

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

pub fn BigComplex::of_real(BigFloat) -> Self

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

pub fn BigComplex::pow(Self, Self, context? : Context) -> Self 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.

pub fn BigComplex::precision(Self) -> Int32

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

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

sin z at the context's width and direction.

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

sinh z at the context's width and direction.

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

sqrt z at the context's width and direction.

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

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.

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

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.

pub fn BigComplex::to_real(Self, 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.

Fractions

Exact rationals, kept in lowest terms.

pub fn parse_fraction(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.

pub fn repr_fraction(Fraction) -> String

repr(Fraction(3, 4)).

pub(all) struct Fraction { num : @bigint.BigInt den : @bigint.BigInt }

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.

Implements Add (+) · Compare (<, <=, >, >=) · Default (default()) · Eq (== and !=) · Mul (*) · Neg (unary -) · Show (to_string()) · Sub (-) — the methods they promote are public on Fraction.

pub fn Fraction::abs(Self) -> Self

The same value without its sign.

pub fn Fraction::ceil_big(Self) -> @bigint.BigInt

math.ceil, as an integer.

pub fn Fraction::denominator(Self) -> @bigint.BigInt

The denominator, always positive.

pub fn Fraction::divide(Self, Self) -> Self 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.

pub fn Fraction::floor_big(Self) -> @bigint.BigInt

math.floor, as an integer.

pub fn Fraction::floor_divide_big(Self, Self) -> @bigint.BigInt raise Refused

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

pub fn Fraction::format(Self, 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.

pub fn Fraction::is_integer(Self) -> Bool

Whether the value is a whole number.

pub fn Fraction::limit_denominator(Self, max~ : @bigint.BigInt) -> Self raise Refused

The closest fraction whose denominator is at most max.

pub fn Fraction::modulo(Self, Self) -> Self raise Refused

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

pub fn Fraction::new(@bigint.BigInt, @bigint.BigInt) -> Self raise Refused

Fraction(num, den).

pub fn Fraction::numerator(Self) -> @bigint.BigInt

The numerator, with the sign.

pub fn Fraction::of_float(Double) -> Self 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.

pub fn Fraction::of_int(@bigint.BigInt) -> Self

The integer n as a fraction.

pub fn Fraction::pow(Self, @bigint.BigInt) -> Self raise Refused

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.

pub fn Fraction::reciprocal(Self) -> Self raise Refused

1/self.

pub fn Fraction::round(Self, ndigits~ : Int32) -> Self

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

pub fn Fraction::round_big(Self) -> @bigint.BigInt

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

pub fn Fraction::to_double(Self) -> Double raise Refused

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

Numbers

The tower: one value that can be any of the four kinds.

pub fn parse(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.

pub(all) enum Number { Int(@bigint.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.

Implements Add (+) · Eq (== and !=) · Mul (*) · Neg (unary -) · Show (to_string()) · Sub (-) — the methods they promote are public on Number.

pub fn Number::compare_numeric(Self, Self) -> Int32 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.

pub fn Number::divide(Self, Self) -> Self 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.

pub fn Number::equal_numeric(Self, Self) -> Bool

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

pub fn Number::floor_mod(Self, Self) -> Self raise Refused

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

pub fn Number::floordiv(Self, Self) -> Self raise Refused

a // b.

pub fn Number::pow(Self, Self) -> Self raise Refused

a ** b.

pub fn Number::to_double(Self) -> Double raise Refused

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

Formatting

The format-specification mini-language.

pub fn format(Number, StringView) -> String raise Refused

format(value, spec), for any number.

pub fn format_float(Double, StringView) -> String raise Refused

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

pub fn format_int(@bigint.BigInt, StringView) -> String raise Refused

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

Errors

One type, four cases.

pub(all) suberror Refused { Malformed(at~ : Int32, 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.

Implements Show (to_string()) — the method it promotes is public on Refused.