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:
| Package | Helpers it uses |
|---|---|
decimal, decimal_gda | split_decimal_string, round_positive_div, pow5, pow10, digits10, abs_bigint, bigint_zero, bigint_one, DecimalExponentBounds, decimal_exponent_limit, CertifiedRefinementBudget, certified_failure |
binary, interval | CertifiedRefinementBudget, 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 and etop is
. 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 and .
pub fn bigint_zero() -> @bigint.BigInt
pub fn bigint_one() -> @bigint.BigInt
abs_bigint, compare_abs
abs_bigint(x) is , and compare_abs(a, b) compares with .
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 and .
pub fn pow5(Int) -> @bigint.BigInt
pub fn pow10(Int) -> @bigint.BigInt
They abort when . pow5 and pow10 read a
process-wide cache that starts with and is extended on demand up to
; larger powers are computed each time without caching.
digits10
digits10(x) is the number of decimal digits of , with
digits10(0) == 1.
pub fn digits10(@bigint.BigInt) -> Int
For it returns the unique with , 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 and the sign are preserved and the new coefficient is not divisible by 10. Zero gives .
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 with , , and
maximal subject to max_drop. A negative max_drop (the default
) sets the limit to digits10(c) - 1, which never binds because a
non-zero integer with trailing zeros has at least digits; so the
default removes every trailing zero. Zero gives . 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 to an
integer magnitude.
pub fn round_positive_div(@bigint.BigInt, @bigint.BigInt, Bool, @arithmetic.RoundingMode) -> @bigint.BigInt
Requires and (aborts otherwise). negative is the sign of
the real quotient whose magnitude is ; the result is
, where rounds to
an integer:
mode | result for , |
|---|---|
TowardZero | |
TowardPositive | |
TowardNegative | |
AwayFromZero | |
ToNearestEven |
The result is exact (equal to ) exactly when .
///|
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 it returns unchanged (it never shifts left). should be
non-negative; this is not checked. For a negative the quotient is the
floor of an arithmetic shift and the remainder is
non-negative, so the table above no longer describes the rounding of :
round_shift(-5N, 1, false, TowardZero) is , not .
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 satisfies
, where is the
string of all mantissa digits (leading zeros kept) and is the written
exponent minus the number of fraction digits. In the wide form the written
exponent is exact up to in magnitude and saturates there, which is
far outside every exponent range. split_decimal_string returns None when
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 , where is
numerator_ and the scale = 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 (aborts if ); from_int(k) is
; 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: and 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
and the smallest dyadic with scale :
and
.
pub fn CertifiedDyadic::round_down(Self, Int) -> Self
pub fn CertifiedDyadic::round_up(Self, Int) -> Self
Abort if . When 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: rounds down to and up to at scale .
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 between two dyadics of
scale .
pub fn certified_dyadic_fraction(@bigint.BigInt, @bigint.BigInt, Int) -> Result[CertifiedInterval[CertifiedDyadic], @arithmetic.ArithmeticError]
The result is for either sign of : it contains , has width or , and is a point exactly when . A non-positive gives a domain error.
certified_dyadic_div
certified_dyadic_div(a, b, s) encloses the quotient of two dyadics at
scale .
pub fn certified_dyadic_div(CertifiedDyadic, CertifiedDyadic, Int) -> Result[CertifiedInterval[CertifiedDyadic], @arithmetic.ArithmeticError]
gives a division-by-zero error. Otherwise the result is
certified_dyadic_fraction applied to 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 with zero
refinements. limit is Some(n), a limit of refinements (default
Some(12)), or None, no count limit. next() increases the precision by
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