A minimal library for representing rational numbers (ratios of integers).
```rust // Rationals are automatically reduced when created: let onehalf = Rational::new(1, 2); let twoquarters = Rational::new(2, 4); asserteq!(onehalf, two_quarters);
// From
is implemented for integers and integer tuples:
asserteq!(Rational::from(1), Rational::new(1, 1));
asserteq!(Rational::from((1, 2)), Rational::new(1, 2));
// The new
method takes a numerator and denominator that implement Into<Rational>
:
let onehalfoveronequarter = Rational::new((1, 2), (1, 4));
asserteq!(onehalfoverone_quarter, Rational::new(2, 1));
```
rust
// Operations and comparisons are implemented for Rationals and integers:
let one_ninth = Rational::new(1, 9);
assert_eq!(one_ninth + Rational::new(5, 4), Rational::new(49, 36));
assert_eq!(one_ninth - 4, Rational::new(-35, 9));
assert_eq!(one_ninth / Rational::new(21, 6), Rational::new(2, 63));
assert!(one_ninth < Rational::new(1, 8));
assert!(one_ninth < 1);
```rust // Inverse: let eightthirds = Rational::new(8, 3); let inverse = eightthirds.inverse(); assert_eq!(inverse, Rational::new(3, 8));
// Mixed fractions: let (whole, fractional) = eightthirds.mixedfraction(); asserteq!(whole, 2); asserteq!(fractional, Rational::new(2, 3)); ```
num-traits
feature to gain access to implementations of many of the traits defined in the num-traits
crate for Rationals