#rational #ratio #fraction

rational

Minimalistic library for rational numbers

15 releases (stable)

1.7.0 Apr 2, 2025
1.6.0 Oct 6, 2024
1.5.0 Oct 30, 2023
1.2.2 Jun 30, 2023
0.2.3 Jul 10, 2021

#153 in Math

Download history 15/week @ 2025-01-15 28/week @ 2025-01-22 5/week @ 2025-01-29 33/week @ 2025-02-05 44/week @ 2025-02-12 5/week @ 2025-02-19 33/week @ 2025-02-26 23/week @ 2025-03-05 58/week @ 2025-03-12 257/week @ 2025-03-19 20/week @ 2025-03-26 146/week @ 2025-04-02 26/week @ 2025-04-09 23/week @ 2025-04-16 26/week @ 2025-04-23 71/week @ 2025-04-30

152 downloads per month

MIT license

85KB
2K SLoC

A minimal library for representing rational numbers.

Construction

// Rationals are automatically reduced when created:
let one_half = Rational::new(1, 2);
let two_quarters = Rational::new(2, 4);
assert_eq!(one_half, two_quarters);

// `From` is implemented for integers and integer tuples:
assert_eq!(Rational::from(1), Rational::new(1, 1));
assert_eq!(Rational::from((1, 2)), Rational::new(1, 2));

// The `new` method takes a numerator and denominator that implement `Into<Rational>`:
let one_half_over_one_quarter = Rational::new((1, 2), (1, 4));
assert_eq!(one_half_over_one_quarter, Rational::new(2, 1));

Mathematical operations

// 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);

Other properties

// Inverse:
let eight_thirds = Rational::new(8, 3);
let inverse = eight_thirds.inverse();
assert_eq!(inverse, Rational::new(3, 8));

// Mixed fractions:
let (whole, fractional) = eight_thirds.mixed_fraction();
assert_eq!(whole, 2);
assert_eq!(fractional, Rational::new(2, 3));

Features

  • num-traits: Enables implementations of many of the traits defined in the num-traits crate for Rationals
  • serde: Enables Deserialize and Serialize implementations for Rational

Dependencies

~185KB