#有理数 #分数 #比例

rational

最小化有理数库

13个版本 (8个稳定版)

1.5.0 2023年10月30日
1.2.2 2023年6月30日
1.1.0 2023年1月4日
1.0.0 2021年8月16日
0.2.3 2021年7月10日

#180 in 数学

每月32次下载

MIT 许可证

78KB
1.5K SLoC

表示有理数(整数比例)的最小库。

构造

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

数学运算

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

其他属性

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

功能

  • 启用 num-traits 功能以访问 num-traits crate 中定义的许多 traits 的实现

依赖关系

~38KB