internal API

Purpose

internal holds exact integer and rational helpers for the numeric cores: powers of 2, 5 and 10, digit counting, removal of trailing factors, integer division with an explicit rounding mode, a decimal string splitter, reduced rationals, dyadic enclosures and the refinement budget of the certified elementary functions. It is an internal package: it cannot be imported from outside Luna-Flow/floating, and its interface may change without notice. The design page proves the rounding and enclosure invariants; the tutorial shows how the helpers combine.

Not every helper is used by every core. On the current branch the library code uses:

PackageHelpers it uses
decimal, decimal_gdasplit_decimal_string, round_positive_div, pow5, pow10, digits10, abs_bigint, bigint_zero, bigint_one, DecimalExponentBounds, decimal_exponent_limit, CertifiedRefinementBudget, certified_failure
binary, intervalCertifiedRefinementBudget, certified_failure

The binary and decimal cores round their own coefficients with their own kernels. The remaining helpers (round_shift, remove_factor10, trim_trailing_decimal_zeros, exact_divide_by_power_of_ten, compare_abs and the CertifiedDyadic family) are exercised by the tests of this package and of the cores only. semantic no longer uses internal: it owns its exact rational (ExactRational) and its normalization.

Decimal exponent bounds

DecimalExponentBounds validates the adopted decNumber decContext.h limits used by both decimal cores and computes the context-derived exponent endpoints without Int wraparound. Precision must be in 1..=999,999,999, e_min in -999,999,999..=0, and e_max in 0..=999,999,999. GDA 1.70 specifies no fixed context limits and requires a balanced exponent range; that separate balance rule is not enforced here.

pub struct DecimalExponentBounds {
  valid_ : Bool
  etiny_ : Int
  etop_ : Int
}
pub fn DecimalExponentBounds::new(Int, Int, Int) -> Self
pub fn DecimalExponentBounds::is_valid(Self) -> Bool
pub fn DecimalExponentBounds::etiny(Self) -> Int
pub fn DecimalExponentBounds::etop(Self) -> Int

For valid inputs, etiny is emin⁡−p+1e_{\min} - p + 1 and etop is emax⁡−p+1e_{\max} - p + 1. Invalid inputs set is_valid() to false; the returned endpoints are clamped only to keep this internal value total, and callers must reject the context before using them.

Importing

Inside the module, add the package to moon.pkg:

import {
  "Luna-Flow/floating/internal",
}

The examples call the package as @internal. and Luna-Flow/arithmetic as @lf_arith.; BigInt literals are written 12N. The interface prints Luna-Flow/arithmetic as @arithmetic (RoundingMode, ArithmeticError, CertificationStage, CertificationFailureReason) and uses @def.Sign.

Integer basics

bigint_zero, bigint_one

These functions return the BigInt constants 00 and 11.

pub fn bigint_zero() -> @bigint.BigInt
pub fn bigint_one() -> @bigint.BigInt

abs_bigint, compare_abs

abs_bigint(x) is ∣x∣|x|, and compare_abs(a, b) compares ∣a∣|a| with ∣b∣|b|.

pub fn abs_bigint(@bigint.BigInt) -> @bigint.BigInt
pub fn compare_abs(@bigint.BigInt, @bigint.BigInt) -> Int

compare_abs returns a negative, zero or positive Int (the result of BigInt::compare on the magnitudes).

///|
test "integer basics" {
  inspect(@internal.abs_bigint(-7N), content="7")
  inspect(@internal.compare_abs(-3N, 2N) > 0, content="true")
}

Powers

pow5, pow10

These functions return 5n5^n and 10n10^n.

pub fn pow5(Int) -> @bigint.BigInt
pub fn pow10(Int) -> @bigint.BigInt

They abort when n<0n < 0. pow5 and pow10 read a process-wide cache that starts with n≤18n \le 18 and is extended on demand up to n=4096n = 4096; larger powers are computed each time without caching.

digits10

digits10(x) is the number of decimal digits of ∣x∣|x|, with digits10(0) == 1.

pub fn digits10(@bigint.BigInt) -> Int

For x≠0x \ne 0 it returns the unique dd with 10d−1≤∣x∣<10d10^{d-1} \le |x| < 10^{d}, starting from an estimate based on the bit length and correcting it with comparisons against powers of ten (no decimal string is built).

///|
test "powers and digit counts" {
  inspect(@internal.pow5(3), content="125")
  inspect(@internal.digits10(0N), content="1")
  inspect(@internal.digits10(-999N), content="3")
  inspect(@internal.digits10(@internal.pow10(5000)), content="5001")
}

Trailing factors

remove_factor10

remove_factor10(coeff, exp) removes all factors 10 from coeff, adjusting the decimal exponent.

pub fn remove_factor10(@bigint.BigInt, Int) -> (@bigint.BigInt, Int)

The value coeff⋅10exp\mathit{coeff} \cdot 10^{\mathit{exp}} and the sign are preserved and the new coefficient is not divisible by 10. Zero gives (0,0)(0, 0).

trim_trailing_decimal_zeros

trim_trailing_decimal_zeros(coeff, exp, max_drop?) removes up to max_drop trailing decimal zeros.

pub fn trim_trailing_decimal_zeros(@bigint.BigInt, Int, max_drop? : Int) -> (@bigint.BigInt, Int, Int)

It returns (c′,e′,k)(c', e', k) with c=c′⋅10kc = c' \cdot 10^{k}, e′=e+ke' = e + k, and kk maximal subject to k≤k \le max_drop. A negative max_drop (the default −1-1) sets the limit to digits10(c) - 1, which never binds because a non-zero integer with kk trailing zeros has at least k+1k + 1 digits; so the default removes every trailing zero. Zero gives (0,0,0)(0, 0, 0). A limit lets a caller stop at a target exponent, as decNumber-style trimming to an ideal exponent does.

exact_divide_by_power_of_ten

exact_divide_by_power_of_ten(coeff, shift) is Some(coeff / 10^shift) when the division is exact and None otherwise.

pub fn exact_divide_by_power_of_ten(@bigint.BigInt, Int) -> @bigint.BigInt?

The sign is kept. Zero gives Some(0) for every shift; for a non-zero coefficient a negative shift aborts.

///|
test "trailing factors" {
  debug_inspect(@internal.remove_factor10(-1200N, 3), content="(-12, 5)")
  debug_inspect(
    @internal.trim_trailing_decimal_zeros(1000N, 0, max_drop=2),
    content="(10, 2, 2)",
  )
  debug_inspect(@internal.exact_divide_by_power_of_ten(1201N, 2), content="None")
}

Rounding integer quotients

round_positive_div

round_positive_div(n, d, negative, mode) rounds the quotient n/dn/d to an integer magnitude.

pub fn round_positive_div(@bigint.BigInt, @bigint.BigInt, Bool, @arithmetic.RoundingMode) -> @bigint.BigInt

Requires n≥0n \ge 0 and d>0d > 0 (aborts otherwise). negative is the sign of the real quotient whose magnitude is n/dn/d; the result is ∣∘mode((−1)negative n/d)∣|\circ_{\text{mode}}((-1)^{\text{negative}}\, n/d)|, where ∘\circ rounds to an integer:

moderesult for n=qd+rn = qd + r, 0≤r<d0 \le r < d
TowardZeroqq
TowardPositiveq+[r>0∧¬negative]q + [r > 0 \wedge \neg\text{negative}]
TowardNegativeq+[r>0∧negative]q + [r > 0 \wedge \text{negative}]
AwayFromZeroq+[r>0]q + [r > 0]
ToNearestEvenq+[2r>d∨(2r=d∧q odd)]q + [2r > d \vee (2r = d \wedge q \text{ odd})]

The result is exact (equal to n/dn/d) exactly when r=0r = 0.

///|
test "rounding -5/2 and -7/2" {
  let modes = [
    @lf_arith.RoundingMode::ToNearestEven,
    @lf_arith.RoundingMode::TowardZero,
    @lf_arith.RoundingMode::TowardPositive,
    @lf_arith.RoundingMode::TowardNegative,
    @lf_arith.RoundingMode::AwayFromZero,
  ]
  let five = modes.map(m => @internal.round_positive_div(5N, 2N, true, m).to_string())
  let seven = modes.map(m => @internal.round_positive_div(7N, 2N, true, m).to_string())
  inspect(five.join(" "), content="2 2 2 3 3")
  inspect(seven.join(" "), content="4 3 3 4 4")
}

round_shift

round_shift(m, s, negative, mode) is round_positive_div(m, 2^s, negative, mode) computed with shifts.

pub fn round_shift(@bigint.BigInt, Int, Bool, @arithmetic.RoundingMode) -> @bigint.BigInt

For s≤0s \le 0 it returns mm unchanged (it never shifts left). mm should be non-negative; this is not checked. For a negative mm the quotient is the floor ⌊m/2s⌋\lfloor m / 2^{s} \rfloor of an arithmetic shift and the remainder is non-negative, so the table above no longer describes the rounding of ∣m∣|m|: round_shift(-5N, 1, false, TowardZero) is −3-3, not −2-2.

Decimal strings

split_decimal_string, split_decimal_string_wide

split_decimal_string(text) splits a finite decimal literal into sign, digits and exponent; split_decimal_string_wide returns the exponent as an Int64.

pub fn split_decimal_string(String) -> (Bool, String, Int)?
pub fn split_decimal_string_wide(String) -> (Bool, String, Int64)?

The accepted grammar is

[+|-] digit* [. digit*] [(e|E) [+|-] digit+]     with at least one mantissa digit

The result (neg,D,q)(\mathit{neg}, D, q) satisfies value=(−1)neg⋅D⋅10q\text{value} = (-1)^{\mathit{neg}} \cdot D \cdot 10^{q}, where DD is the string of all mantissa digits (leading zeros kept) and qq is the written exponent minus the number of fraction digits. In the wide form the written exponent is exact up to 101810^{18} in magnitude and saturates there, which is far outside every exponent range. split_decimal_string returns None when qq does not fit Int. Anything else, including whitespace, _, inf and nan, gives None.

///|
test "split decimal string" {
  debug_inspect(
    @internal.split_decimal_string("-12.50e3"),
    content="Some((true, \"1250\", 1))",
  )
  debug_inspect(@internal.split_decimal_string(".5"), content="Some((false, \"5\", -1))")
  debug_inspect(@internal.split_decimal_string("1e"), content="None")
  debug_inspect(@internal.split_decimal_string("1e3000000000"), content="None")
  debug_inspect(@internal.split_decimal_string_wide("1e3000000000"), content="Some((false, \"1\", 3000000000))")
}

Dyadic enclosures

CertifiedDyadic

CertifiedDyadic is the dyadic rational n⋅2−sn \cdot 2^{-s}, where nn is numerator_ and the scale ss = scale_ is non-negative.

pub struct CertifiedDyadic {
  numerator_ : @bigint.BigInt
  scale_ : Int
}

The fields are readable but the struct cannot be built literally outside the package; build values with new or from_int.

CertifiedDyadic::new, CertifiedDyadic::from_int, CertifiedDyadic::numerator, CertifiedDyadic::scale

new(n, s) is n⋅2−sn \cdot 2^{-s} (aborts if s<0s < 0); from_int(k) is k⋅20k \cdot 2^{0}; the accessors return the fields.

pub fn CertifiedDyadic::new(@bigint.BigInt, Int) -> Self
pub fn CertifiedDyadic::from_int(Int) -> Self
pub fn CertifiedDyadic::numerator(Self) -> @bigint.BigInt
pub fn CertifiedDyadic::scale(Self) -> Int

The representation is not normalized: 2⋅2−12 \cdot 2^{-1} and 1⋅201 \cdot 2^{0} are different values of the struct with the same number.

CertifiedDyadic::add, CertifiedDyadic::sub, CertifiedDyadic::mul, CertifiedDyadic::neg, CertifiedDyadic::compare

These methods are exact arithmetic and comparison of dyadic numbers.

pub fn CertifiedDyadic::add(Self, Self) -> Self
pub fn CertifiedDyadic::sub(Self, Self) -> Self
pub fn CertifiedDyadic::mul(Self, Self) -> Self
pub fn CertifiedDyadic::neg(Self) -> Self
pub fn CertifiedDyadic::compare(Self, Self) -> Int

add and sub align to the larger scale; mul adds the scales; compare compares the numbers (not the representations), so new(2N, 1).compare(from_int(1)) is 0.

CertifiedDyadic::round_down, CertifiedDyadic::round_up

x.round_down(s) and x.round_up(s) are the largest dyadic ≤x\le x and the smallest dyadic ≥x\ge x with scale ss: ⌊x⋅2s⌋⋅2−s\lfloor x \cdot 2^{s} \rfloor \cdot 2^{-s} and ⌈x⋅2s⌉⋅2−s\lceil x \cdot 2^{s} \rceil \cdot 2^{-s}.

pub fn CertifiedDyadic::round_down(Self, Int) -> Self
pub fn CertifiedDyadic::round_up(Self, Int) -> Self

Abort if s<0s < 0. When ss is at least the current scale the value is re-expressed exactly (the numerator is shifted left). Both directions are true floor and ceiling for negative numbers too: −5/4-5/4 rounds down to −2-2 and up to −1-1 at scale 00.

CertifiedInterval

CertifiedInterval[T] is an ordered pair lower <= upper used as an enclosure.

pub struct CertifiedInterval[T] {
  lower_ : T
  upper_ : T
}

CertifiedInterval::new, CertifiedInterval::lower, CertifiedInterval::upper

new(lower, upper, compare) checks the order with the given comparison and builds the pair; lower and upper return the endpoints.

pub fn[T] CertifiedInterval::new(T, T, (T, T) -> Int) -> Result[Self[T], @arithmetic.ArithmeticError]
pub fn[T] CertifiedInterval::lower(Self[T]) -> T
pub fn[T] CertifiedInterval::upper(Self[T]) -> T

When compare(lower, upper) > 0, new returns a certification-failure error for the operation "interval" with stage EnclosurePropagation, reason InvalidEnclosure, target and working precision 1 and 0 refinements.

certified_dyadic_fraction

certified_dyadic_fraction(n, d, s) encloses n/dn/d between two dyadics of scale ss.

pub fn certified_dyadic_fraction(@bigint.BigInt, @bigint.BigInt, Int) -> Result[CertifiedInterval[CertifiedDyadic], @arithmetic.ArithmeticError]

The result is [⌊n2s/d⌋2−s, ⌈n2s/d⌉2−s][\lfloor n 2^{s}/d \rfloor 2^{-s},\ \lceil n 2^{s}/d \rceil 2^{-s}] for either sign of nn: it contains n/dn/d, has width 00 or 2−s2^{-s}, and is a point exactly when d∣n2sd \mid n 2^{s}. A non-positive dd gives a domain error.

certified_dyadic_div

certified_dyadic_div(a, b, s) encloses the quotient a/ba/b of two dyadics at scale ss.

pub fn certified_dyadic_div(CertifiedDyadic, CertifiedDyadic, Int) -> Result[CertifiedInterval[CertifiedDyadic], @arithmetic.ArithmeticError]

b=0b = 0 gives a division-by-zero error. Otherwise the result is certified_dyadic_fraction applied to a/ba/b written with a positive denominator.

///|
test "one third at scale 8" {
  let third = @internal.certified_dyadic_div(
    @internal.CertifiedDyadic::from_int(1),
    @internal.CertifiedDyadic::from_int(3),
    8,
  ).unwrap()
  inspect(third.lower().numerator(), content="85") // 85/256 <= 1/3
  inspect(third.upper().numerator(), content="86") // 86/256 >= 1/3
  let negative = @internal.certified_dyadic_fraction(-1N, 3N, 2).unwrap()
  inspect(negative.lower().numerator(), content="-2") // -2/4 <= -1/3
  inspect(negative.upper().numerator(), content="-1") // -1/4 >= -1/3
}

Refinement budgets

CertifiedRefinementBudget

CertifiedRefinementBudget tracks the working precision and the number of refinements of a Ziv-style evaluation loop.

pub struct CertifiedRefinementBudget {
  work_precision : Int
  refinements_ : Int
  limit_ : Int?
  cap_ : Int
}

CertifiedRefinementBudget::new, CertifiedRefinementBudget::next, CertifiedRefinementBudget::available, CertifiedRefinementBudget::precision, CertifiedRefinementBudget::refinements

new(p, limit?) starts at working precision max⁡(1,p)\max(1, p) with zero refinements. limit is Some(n), a limit of max⁡(1,n)\max(1, n) refinements (default Some(12)), or None, no count limit. next() increases the precision by max⁡(32,⌊p/2⌋)\max(32, \lfloor p/2 \rfloor) and counts one refinement. available() is true while fewer than n refinements were made, and, for None, while the working precision does not exceed certified_unbounded_work_cap of the starting precision.

pub fn CertifiedRefinementBudget::new(Int, limit? : Int?) -> Self
pub fn CertifiedRefinementBudget::next(Self) -> Self
pub fn CertifiedRefinementBudget::available(Self) -> Bool
pub fn CertifiedRefinementBudget::precision(Self) -> Int
pub fn CertifiedRefinementBudget::refinements(Self) -> Int

next does not check available; a loop must test available() itself.

///|
test "budget schedule" {
  let mut budget = @internal.CertifiedRefinementBudget::new(64, limit=Some(3))
  let seen = []
  while budget.available() {
    seen.push(budget.precision().to_string())
    budget = budget.next()
  }
  inspect(seen.join(" -> "), content="64 -> 96 -> 144")
  inspect(budget.precision(), content="216")
  inspect(budget.refinements(), content="3")
}

certified_refinement_continues, certified_unbounded_work_cap

certified_refinement_continues(limit, attempt, work, precision) tells a hand-written refinement loop whether it may run another step: Some(n) allows attempt < max(1, n), None allows the step while work does not exceed certified_unbounded_work_cap(precision). That cap is the larger of 8,000,000 and 256 times precision, at most 1,000,000,000.

pub fn certified_refinement_continues(Int?, Int, Int, Int) -> Bool
pub fn certified_unbounded_work_cap(Int) -> Int

certified_failure

certified_failure(operation, stage, reason, target_precision, budget) builds the ArithmeticError a certified operation returns when it gives up.

pub fn certified_failure(String, @arithmetic.CertificationStage, @arithmetic.CertificationFailureReason, Int, CertifiedRefinementBudget) -> @arithmetic.ArithmeticError

The error’s detail records the operation name, stage, reason, target precision, and the budget’s current working precision and refinement count.

Complete public interface

This snapshot is the generated pkg.generated.mbti of the package. It is the authority when prose and interface disagree.

// Generated using `moon info`, DON'T EDIT IT
package "Luna-Flow/floating/internal"

import {
  "Luna-Flow/arithmetic",
  "moonbitlang/core/bigint",
}

// Values
pub fn abs_bigint(@bigint.BigInt) -> @bigint.BigInt

pub fn bigint_one() -> @bigint.BigInt

pub fn bigint_zero() -> @bigint.BigInt

pub fn certified_dyadic_div(CertifiedDyadic, CertifiedDyadic, Int32) -> Result[CertifiedInterval[CertifiedDyadic], @arithmetic.ArithmeticError]

pub fn certified_dyadic_fraction(@bigint.BigInt, @bigint.BigInt, Int32) -> Result[CertifiedInterval[CertifiedDyadic], @arithmetic.ArithmeticError]

pub fn certified_failure(String, @arithmetic.CertificationStage, @arithmetic.CertificationFailureReason, Int32, CertifiedRefinementBudget) -> @arithmetic.ArithmeticError

pub fn certified_refinement_continues(Int32?, Int32, Int32, Int32) -> Bool

pub fn certified_unbounded_work_cap(Int32) -> Int32

pub fn compare_abs(@bigint.BigInt, @bigint.BigInt) -> Int32

pub let decimal_exponent_limit : Int32

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

pub fn exact_divide_by_power_of_ten(@bigint.BigInt, Int32) -> @bigint.BigInt?

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

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

pub fn remove_factor10(@bigint.BigInt, Int32) -> (@bigint.BigInt, Int32)

pub fn round_positive_div(@bigint.BigInt, @bigint.BigInt, Bool, @arithmetic.RoundingMode) -> @bigint.BigInt

pub fn round_shift(@bigint.BigInt, Int32, Bool, @arithmetic.RoundingMode) -> @bigint.BigInt

pub fn split_decimal_string(String) -> (Bool, String, Int32)?

pub fn split_decimal_string_wide(String) -> (Bool, String, Int64)?

pub fn trim_trailing_decimal_zeros(@bigint.BigInt, Int32, max_drop? : Int32) -> (@bigint.BigInt, Int32, Int32)

// Errors

// Types and methods
pub struct CertifiedDyadic {
  numerator_ : @bigint.BigInt
  scale_ : Int32
}
pub fn CertifiedDyadic::add(Self, Self) -> Self
pub fn CertifiedDyadic::compare(Self, Self) -> Int32
pub fn CertifiedDyadic::from_int(Int32) -> Self
pub fn CertifiedDyadic::mul(Self, Self) -> Self
pub fn CertifiedDyadic::neg(Self) -> Self
pub fn CertifiedDyadic::new(@bigint.BigInt, Int32) -> Self
pub fn CertifiedDyadic::numerator(Self) -> @bigint.BigInt
pub fn CertifiedDyadic::round_down(Self, Int32) -> Self
pub fn CertifiedDyadic::round_up(Self, Int32) -> Self
pub fn CertifiedDyadic::scale(Self) -> Int32
pub fn CertifiedDyadic::sub(Self, Self) -> Self

pub struct CertifiedInterval[T] {
  lower_ : T
  upper_ : T
}
pub fn[T] CertifiedInterval::lower(Self[T]) -> T
pub fn[T] CertifiedInterval::new(T, T, (T, T) -> Int32) -> Result[Self[T], @arithmetic.ArithmeticError]
pub fn[T] CertifiedInterval::upper(Self[T]) -> T

pub struct CertifiedRefinementBudget {
  work_precision : Int32
  refinements_ : Int32
  limit_ : Int32?
  cap_ : Int32
}
pub fn CertifiedRefinementBudget::available(Self) -> Bool
pub fn CertifiedRefinementBudget::new(Int32, limit? : Int32?) -> Self
pub fn CertifiedRefinementBudget::next(Self) -> Self
pub fn CertifiedRefinementBudget::precision(Self) -> Int32
pub fn CertifiedRefinementBudget::refinements(Self) -> Int32

pub struct DecimalExponentBounds {
  valid_ : Bool
  etiny_ : Int32
  etop_ : Int32
}
pub fn DecimalExponentBounds::etiny(Self) -> Int32
pub fn DecimalExponentBounds::etop(Self) -> Int32
pub fn DecimalExponentBounds::is_valid(Self) -> Bool
pub fn DecimalExponentBounds::new(Int32, Int32, Int32) -> Self

// Type aliases

// Traits