Skip to main content

Module numeric

Module numeric 

Source
Expand description

Exact conversions between machine floats and rationals.

Every finite f64 is a dyadic rational m · 2^e, so it can be converted to a Ratio<BigInt> exactly — no rounding, no chosen denominator. That is the right default for a library whose core promise is exact arithmetic: 0.1_f64 really is 3602879701896397/36028797018963968, and pretending otherwise hides error.

When the caller wants the “nice” rational a human meant (0.1 → 1/10), use f64_to_ratio_approx, which returns the best rational approximation with a bounded denominator (Stern–Brocot / continued-fraction convergents), or the higher-level Context::from_f64_approx.

These two functions replace the several ad-hoc (x * 10^k).round() helpers that used to be scattered through the crate, each with a different scale and each silently saturating on large inputs.

Functions§

best_rational_approx
Best rational approximation to target with denominator ≤ max_denom, via continued-fraction convergents and the final semiconvergent.
f64_to_ratio_approx
Best rational approximation to x with denominator at most max_denom.
f64_to_ratio_exact
Convert a finite f64 to the exact rational it represents.
is_perfect_square
Integer square root helper for tests and callers that need exactness.
ratio_to_f64
Convert a rational to the nearest f64, returning None if it does not fit (overflow to ±∞ is reported as None).