def tutorial
The goal of this tutorial is to write code that works with every number type
of floating at once: you inspect values through the Floating trait, test
their class with the generic predicates, read IEEE comparison results as
PartialOrder, and reuse the arithmetic context and error types that def
re-exports. def itself does no arithmetic; the concrete packages
(binary, decimal,
decimal_gda) do. Intervals (interval) are not Floating. The laws
behind the trait are in the design page.
| I want to | Use |
|---|---|
| ask any value for its class, sign or precision | Floating |
| test for NaN, infinity or zero generically | is_nan, is_infinite, is_finite, is_zero |
| round a value to fewer digits of its own radix | Floating::with_precision |
| read the result of an IEEE comparison | PartialOrder |
| compare decimal cohorts by their printed form | Floating::normalized |
handle checked errors without importing arithmetic | ArithmeticError |
Quick start
Add the module and import def next to the representation you use:
moon add Luna-Flow/floating@0.11.0
import {
"Luna-Flow/floating/def",
"Luna-Flow/floating/binary",
}
The smallest useful program asks a value what it is:
///|
test "quick start: observe a value" {
let x = @binary.Binary::from_double(-2.5)
inspect(@def.is_finite(x), content="true")
inspect(@def.Floating::signum(x) == @def.Sign::Negative, content="true")
inspect(@def.Floating::precision(x), content="53")
}
Everyday tasks
Write one function for every representation
A function bounded by F : @def.Floating accepts binary, IEEE decimal and GDA
decimal values. Call the trait methods in their qualified form,
@def.Floating::classify(x), because MoonBit no longer turns trait methods
into dot methods of a type parameter.
///|
fn[F : @def.Floating] summary(x : F) -> String {
if @def.is_nan(x) {
return "nan"
}
let sign = match @def.Floating::signum(x) {
Negative => "negative"
Zero => "zero"
Positive => "positive"
}
let kind = if @def.is_infinite(x) { "infinite" } else { "finite" }
"\{kind} \{sign} at precision \{@def.Floating::precision(x)}"
}
///|
test "one summary for four representations" {
inspect(
summary(@binary.Binary::from_int(7)),
content="finite positive at precision 53",
)
inspect(
summary(@decimal.Decimal::from_string("-0.00").unwrap()),
content="finite zero at precision 34",
)
inspect(
summary(@decimal_gda.Decimal::from_string("-Infinity").unwrap()),
content="infinite negative at precision 34",
)
}
Change precision generically
with_precision rounds to the requested number of significant digits of the
value’s own radix, bits for binary and digits for decimal, to nearest with ties
to even. The trait method takes no rounding mode; a concrete type has its own
with_precision method that does:
///|
fn[F : @def.Floating] three_digits(x : F) -> F {
@def.Floating::with_precision(x, 3)
}
///|
test "round to three significant digits of the radix" {
let d = three_digits(@decimal.Decimal::from_string("3.14159").unwrap())
inspect(d.to_string(), content="3.14")
let b = three_digits(@binary.Binary::from_int(11))
inspect(b.to_string(), content="3p2")
}
Eleven is 1011 in binary; three significant bits round it to 1100, which
to_string prints as .
Read an IEEE comparison
Comparisons that follow IEEE 754 return a PartialOrder, whose fourth value
Unordered reports a NaN operand:
///|
fn relation(a : @binary.Binary, b : @binary.Binary) -> String {
match a.compare_quiet(b).0 {
Less => "less"
Equal => "equal"
Greater => "greater"
Unordered => "unordered"
}
}
///|
test "four-way comparison" {
let one = @binary.Binary::from_int(1)
let two = @binary.Binary::from_int(2)
inspect(relation(one, two), content="less")
inspect(relation(@binary.Binary::nan(), @binary.Binary::nan()), content="unordered")
inspect(
relation(@binary.Binary::from_double(-0.0), @binary.Binary::zero()),
content="equal",
)
}
Normalize before comparing representations
Decimal values with the same value can differ in their stored exponent
(1.5 and 1.500 belong to one cohort). normalized picks the canonical
member, so the printed forms agree:
///|
test "normalize a decimal cohort" {
let a = @decimal.Decimal::from_string("1.500").unwrap()
let b = @decimal.Decimal::from_string("1.5").unwrap()
inspect(a.to_string(), content="1.500")
inspect(
@def.Floating::normalized(a).to_string() ==
@def.Floating::normalized(b).to_string(),
content="true",
)
}
Going further
Use the re-exported arithmetic types
@def.ArithmeticContext, @def.ArithmeticError, @def.RoundingMode and the
other aliases are the types of Luna-Flow/arithmetic.
Code that only needs the vocabulary can import def instead of arithmetic:
///|
fn describe_error(e : @def.ArithmeticError) -> String {
if e.is_division_by_zero() {
"division by zero: " + e.message
} else if e.is_domain_error() {
"domain error: " + e.message
} else {
"other: " + e.message
}
}
///|
test "handle a checked result through def" {
let result = @lf_arith.DivChecked::div_checked(
@binary.Binary::from_int(1),
@binary.Binary::zero(),
@lf_arith.ArithmeticContext::new(53),
)
match result {
Ok(_) => fail("expected an error")
Err(e) => inspect(describe_error(e), content="division by zero: division by zero")
}
}
Common pitfalls
Sign::Zerodoes not mean “the value is zero”. It is also returned for NaN by the scalar types. Test@def.is_nanfirst.Intervalis notFloating: ask an intervalis_empty,is_common_intervalorcontains.Signcannot tell from . Use the concrete package (Binary::is_negative_zero,Decimal::is_sign_minus) when the sign bit matters.PartialOrderis not an ordering you can sort with:Unorderedbreaks trichotomy. Use the total orders of the concrete packages (Binary::total_order_compare,Decimal::total_order_compare) for sorting.with_precisionreports no flags and ignores context exponent limits (aBinarystill overflows at its implementation range of about ). When rounding must be observed, use the*_ctxoperations of the concrete package.with_precision(x, 0)is not an error: the precision is clamped to 1.
Next steps
defdesign: the trait laws and the order theory ofPartialOrder.defAPI: every item with its signature.semantictutorial: compare values of different representations exactly.- Numeric semantics guide for the shared vocabulary of the repository.