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
targetwith denominator≤ max_denom, via continued-fraction convergents and the final semiconvergent. - f64_
to_ ratio_ approx - Best rational approximation to
xwith denominator at mostmax_denom. - f64_
to_ ratio_ exact - Convert a finite
f64to 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, returningNoneif it does not fit (overflow to ±∞ is reported asNone).