pub struct Rational { /* private fields */ }Expand description
An exact rational number: a fraction kept in lowest terms with a strictly
positive denominator. Built on BigInt, so it never rounds the way a JSON
/ f64 “number” does — 1/3 stays exactly 1/3, not 0.3333…, and a
numerator past 2^53 survives instead of collapsing onto a double.
Representation is correct-first: BigInt numerator and denominator, reduced on
every construction. The i64-fast-path (storing small num/den inline to skip
the BigInt allocation) is the documented performance follow-up — exactly as
Karatsuba is for BigInt — and must reproduce these values bit-for-bit.
Implementations§
Source§impl Rational
impl Rational
Sourcepub fn new(num: BigInt, den: BigInt) -> Option<Rational>
pub fn new(num: BigInt, den: BigInt) -> Option<Rational>
The canonicalizing constructor: reduce num/den to lowest terms with a
positive denominator. Returns None for a zero denominator (the one
undefined fraction).
Sourcepub fn from_bigint(n: BigInt) -> Rational
pub fn from_bigint(n: BigInt) -> Rational
The integer n as the fraction n/1.
pub fn from_i64(x: i64) -> Rational
Sourcepub fn from_ratio_i64(n: i64, d: i64) -> Option<Rational>
pub fn from_ratio_i64(n: i64, d: i64) -> Option<Rational>
n/d from machine integers (convenience; None if d == 0).
pub fn zero() -> Rational
pub fn one() -> Rational
pub fn numerator(&self) -> &BigInt
pub fn denominator(&self) -> &BigInt
Sourcepub fn is_integer(&self) -> bool
pub fn is_integer(&self) -> bool
True when the value is a whole number (den == 1).
pub fn is_zero(&self) -> bool
pub fn is_negative(&self) -> bool
pub fn is_positive(&self) -> bool
Sourcepub fn to_bigint(&self) -> Option<BigInt>
pub fn to_bigint(&self) -> Option<BigInt>
The integer value when this is whole, else None (the provable narrow
back to BigInt).
Sourcepub fn to_i64(&self) -> Option<i64>
pub fn to_i64(&self) -> Option<i64>
The i64 value when this is a whole number that fits, else None.
Sourcepub fn to_f64(&self) -> f64
pub fn to_f64(&self) -> f64
Nearest f64 (for display / interop only — lossy for large terms, exact
for small ones). The value stays exact; this is a view.
Sourcepub fn floor(&self) -> BigInt
pub fn floor(&self) -> BigInt
The greatest integer ≤ self (round toward −∞). floor(7/2) == 3,
floor(-7/2) == -4. The companion of explicit floor division.
Sourcepub fn ceil(&self) -> BigInt
pub fn ceil(&self) -> BigInt
The least integer ≥ self (round toward +∞). ceil(7/2) == 4,
ceil(-7/2) == -3.
Sourcepub fn round(&self) -> BigInt
pub fn round(&self) -> BigInt
The nearest integer, ties rounded AWAY from zero (matching f64::round):
round(x) = sign(x) · ⌊|x| + 1/2⌋ = sign(x) · ((2|num| + den) ÷ 2den).