rational.rs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822
  1. // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
  2. // file at the top-level directory of this distribution and at
  3. // http://rust-lang.org/COPYRIGHT.
  4. //
  5. // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
  6. // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
  7. // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
  8. // option. This file may not be copied, modified, or distributed
  9. // except according to those terms.
  10. //! Rational numbers
  11. use Integer;
  12. use std::cmp;
  13. use std::fmt;
  14. use std::ops::{Add, Div, Mul, Neg, Rem, Sub};
  15. use std::str::FromStr;
  16. use std::num::{FromPrimitive, FromStrRadix, Float};
  17. use bigint::{BigInt, BigUint, Sign};
  18. use {Num, Signed, Zero, One};
  19. /// Represents the ratio between 2 numbers.
  20. #[derive(Copy, Clone, Hash, RustcEncodable, RustcDecodable)]
  21. #[allow(missing_docs)]
  22. pub struct Ratio<T> {
  23. numer: T,
  24. denom: T
  25. }
  26. /// Alias for a `Ratio` of machine-sized integers.
  27. pub type Rational = Ratio<int>;
  28. pub type Rational32 = Ratio<i32>;
  29. pub type Rational64 = Ratio<i64>;
  30. /// Alias for arbitrary precision rationals.
  31. pub type BigRational = Ratio<BigInt>;
  32. impl<T: Clone + Integer + PartialOrd>
  33. Ratio<T> {
  34. /// Creates a ratio representing the integer `t`.
  35. #[inline]
  36. pub fn from_integer(t: T) -> Ratio<T> {
  37. Ratio::new_raw(t, One::one())
  38. }
  39. /// Creates a ratio without checking for `denom == 0` or reducing.
  40. #[inline]
  41. pub fn new_raw(numer: T, denom: T) -> Ratio<T> {
  42. Ratio { numer: numer, denom: denom }
  43. }
  44. /// Create a new Ratio. Fails if `denom == 0`.
  45. #[inline]
  46. pub fn new(numer: T, denom: T) -> Ratio<T> {
  47. if denom == Zero::zero() {
  48. panic!("denominator == 0");
  49. }
  50. let mut ret = Ratio::new_raw(numer, denom);
  51. ret.reduce();
  52. ret
  53. }
  54. /// Converts to an integer.
  55. #[inline]
  56. pub fn to_integer(&self) -> T {
  57. self.trunc().numer
  58. }
  59. /// Gets an immutable reference to the numerator.
  60. #[inline]
  61. pub fn numer<'a>(&'a self) -> &'a T {
  62. &self.numer
  63. }
  64. /// Gets an immutable reference to the denominator.
  65. #[inline]
  66. pub fn denom<'a>(&'a self) -> &'a T {
  67. &self.denom
  68. }
  69. /// Returns true if the rational number is an integer (denominator is 1).
  70. #[inline]
  71. pub fn is_integer(&self) -> bool {
  72. self.denom == One::one()
  73. }
  74. /// Put self into lowest terms, with denom > 0.
  75. fn reduce(&mut self) {
  76. let g : T = self.numer.gcd(&self.denom);
  77. // FIXME(#5992): assignment operator overloads
  78. // self.numer /= g;
  79. self.numer = self.numer.clone() / g.clone();
  80. // FIXME(#5992): assignment operator overloads
  81. // self.denom /= g;
  82. self.denom = self.denom.clone() / g;
  83. // keep denom positive!
  84. if self.denom < Zero::zero() {
  85. self.numer = -self.numer.clone();
  86. self.denom = -self.denom.clone();
  87. }
  88. }
  89. /// Returns a `reduce`d copy of self.
  90. pub fn reduced(&self) -> Ratio<T> {
  91. let mut ret = self.clone();
  92. ret.reduce();
  93. ret
  94. }
  95. /// Returns the reciprocal.
  96. #[inline]
  97. pub fn recip(&self) -> Ratio<T> {
  98. Ratio::new_raw(self.denom.clone(), self.numer.clone())
  99. }
  100. /// Rounds towards minus infinity.
  101. #[inline]
  102. pub fn floor(&self) -> Ratio<T> {
  103. if *self < Zero::zero() {
  104. let one: T = One::one();
  105. Ratio::from_integer((self.numer.clone() - self.denom.clone() + one) / self.denom.clone())
  106. } else {
  107. Ratio::from_integer(self.numer.clone() / self.denom.clone())
  108. }
  109. }
  110. /// Rounds towards plus infinity.
  111. #[inline]
  112. pub fn ceil(&self) -> Ratio<T> {
  113. if *self < Zero::zero() {
  114. Ratio::from_integer(self.numer.clone() / self.denom.clone())
  115. } else {
  116. let one: T = One::one();
  117. Ratio::from_integer((self.numer.clone() + self.denom.clone() - one) / self.denom.clone())
  118. }
  119. }
  120. /// Rounds to the nearest integer. Rounds half-way cases away from zero.
  121. #[inline]
  122. pub fn round(&self) -> Ratio<T> {
  123. let one: T = One::one();
  124. let two: T = one.clone() + one.clone();
  125. // Find unsigned fractional part of rational number
  126. let fractional = self.fract().abs();
  127. // The algorithm compares the unsigned fractional part with 1/2, that
  128. // is, a/b >= 1/2, or a >= b/2. For odd denominators, we use
  129. // a >= (b/2)+1. This avoids overflow issues.
  130. let half_or_larger = if fractional.denom().is_even() {
  131. *fractional.numer() >= fractional.denom().clone() / two.clone()
  132. } else {
  133. *fractional.numer() >= (fractional.denom().clone() / two.clone()) + one.clone()
  134. };
  135. if half_or_larger {
  136. let one: Ratio<T> = One::one();
  137. if *self >= Zero::zero() {
  138. self.trunc() + one
  139. } else {
  140. self.trunc() - one
  141. }
  142. } else {
  143. self.trunc()
  144. }
  145. }
  146. /// Rounds towards zero.
  147. #[inline]
  148. pub fn trunc(&self) -> Ratio<T> {
  149. Ratio::from_integer(self.numer.clone() / self.denom.clone())
  150. }
  151. /// Returns the fractional part of a number.
  152. #[inline]
  153. pub fn fract(&self) -> Ratio<T> {
  154. Ratio::new_raw(self.numer.clone() % self.denom.clone(), self.denom.clone())
  155. }
  156. }
  157. impl Ratio<BigInt> {
  158. /// Converts a float into a rational number.
  159. pub fn from_float<T: Float>(f: T) -> Option<BigRational> {
  160. if !f.is_finite() {
  161. return None;
  162. }
  163. let (mantissa, exponent, sign) = f.integer_decode();
  164. let bigint_sign = if sign == 1 { Sign::Plus } else { Sign::Minus };
  165. if exponent < 0 {
  166. let one: BigInt = One::one();
  167. let denom: BigInt = one << ((-exponent) as uint);
  168. let numer: BigUint = FromPrimitive::from_u64(mantissa).unwrap();
  169. Some(Ratio::new(BigInt::from_biguint(bigint_sign, numer), denom))
  170. } else {
  171. let mut numer: BigUint = FromPrimitive::from_u64(mantissa).unwrap();
  172. numer = numer << (exponent as uint);
  173. Some(Ratio::from_integer(BigInt::from_biguint(bigint_sign, numer)))
  174. }
  175. }
  176. }
  177. /* Comparisons */
  178. // comparing a/b and c/d is the same as comparing a*d and b*c, so we
  179. // abstract that pattern. The following macro takes a trait and either
  180. // a comma-separated list of "method name -> return value" or just
  181. // "method name" (return value is bool in that case)
  182. macro_rules! cmp_impl {
  183. (impl $imp:ident, $($method:ident),+) => {
  184. cmp_impl!(impl $imp, $($method -> bool),+);
  185. };
  186. // return something other than a Ratio<T>
  187. (impl $imp:ident, $($method:ident -> $res:ty),*) => {
  188. impl<T: Clone + Mul<T, Output = T> + $imp> $imp for Ratio<T> {
  189. $(
  190. #[inline]
  191. fn $method(&self, other: &Ratio<T>) -> $res {
  192. (self.numer.clone() * other.denom.clone()). $method (&(self.denom.clone()*other.numer.clone()))
  193. }
  194. )*
  195. }
  196. };
  197. }
  198. cmp_impl!(impl PartialEq, eq, ne);
  199. cmp_impl!(impl PartialOrd, lt -> bool, gt -> bool, le -> bool, ge -> bool,
  200. partial_cmp -> Option<cmp::Ordering>);
  201. cmp_impl!(impl Eq, );
  202. cmp_impl!(impl Ord, cmp -> cmp::Ordering);
  203. macro_rules! forward_val_val_binop {
  204. (impl $imp:ident, $method:ident) => {
  205. impl<T: Clone + Integer + PartialOrd> $imp<Ratio<T>> for Ratio<T> {
  206. type Output = Ratio<T>;
  207. #[inline]
  208. fn $method(self, other: Ratio<T>) -> Ratio<T> {
  209. (&self).$method(&other)
  210. }
  211. }
  212. }
  213. }
  214. macro_rules! forward_ref_val_binop {
  215. (impl $imp:ident, $method:ident) => {
  216. impl<'a, T: Clone + Integer + PartialOrd> $imp<Ratio<T>> for &'a Ratio<T> {
  217. type Output = Ratio<T>;
  218. #[inline]
  219. fn $method(self, other: Ratio<T>) -> Ratio<T> {
  220. self.$method(&other)
  221. }
  222. }
  223. }
  224. }
  225. macro_rules! forward_val_ref_binop {
  226. (impl $imp:ident, $method:ident) => {
  227. impl<'a, T: Clone + Integer + PartialOrd> $imp<&'a Ratio<T>> for Ratio<T> {
  228. type Output = Ratio<T>;
  229. #[inline]
  230. fn $method(self, other: &Ratio<T>) -> Ratio<T> {
  231. (&self).$method(other)
  232. }
  233. }
  234. }
  235. }
  236. macro_rules! forward_all_binop {
  237. (impl $imp:ident, $method:ident) => {
  238. forward_val_val_binop!(impl $imp, $method);
  239. forward_ref_val_binop!(impl $imp, $method);
  240. forward_val_ref_binop!(impl $imp, $method);
  241. };
  242. }
  243. /* Arithmetic */
  244. forward_all_binop!(impl Mul, mul);
  245. // a/b * c/d = (a*c)/(b*d)
  246. impl<'a, 'b, T> Mul<&'b Ratio<T>> for &'a Ratio<T>
  247. where T: Clone + Integer + PartialOrd
  248. {
  249. type Output = Ratio<T>;
  250. #[inline]
  251. fn mul(self, rhs: &Ratio<T>) -> Ratio<T> {
  252. Ratio::new(self.numer.clone() * rhs.numer.clone(), self.denom.clone() * rhs.denom.clone())
  253. }
  254. }
  255. forward_all_binop!(impl Div, div);
  256. // (a/b) / (c/d) = (a*d)/(b*c)
  257. impl<'a, 'b, T> Div<&'b Ratio<T>> for &'a Ratio<T>
  258. where T: Clone + Integer + PartialOrd
  259. {
  260. type Output = Ratio<T>;
  261. #[inline]
  262. fn div(self, rhs: &Ratio<T>) -> Ratio<T> {
  263. Ratio::new(self.numer.clone() * rhs.denom.clone(), self.denom.clone() * rhs.numer.clone())
  264. }
  265. }
  266. // Abstracts the a/b `op` c/d = (a*d `op` b*d) / (b*d) pattern
  267. macro_rules! arith_impl {
  268. (impl $imp:ident, $method:ident) => {
  269. forward_all_binop!(impl $imp, $method);
  270. impl<'a, 'b, T: Clone + Integer + PartialOrd>
  271. $imp<&'b Ratio<T>> for &'a Ratio<T> {
  272. type Output = Ratio<T>;
  273. #[inline]
  274. fn $method(self, rhs: &Ratio<T>) -> Ratio<T> {
  275. Ratio::new((self.numer.clone() * rhs.denom.clone()).$method(self.denom.clone() * rhs.numer.clone()),
  276. self.denom.clone() * rhs.denom.clone())
  277. }
  278. }
  279. }
  280. }
  281. // a/b + c/d = (a*d + b*c)/(b*d)
  282. arith_impl!(impl Add, add);
  283. // a/b - c/d = (a*d - b*c)/(b*d)
  284. arith_impl!(impl Sub, sub);
  285. // a/b % c/d = (a*d % b*c)/(b*d)
  286. arith_impl!(impl Rem, rem);
  287. impl<T> Neg for Ratio<T>
  288. where T: Clone + Integer + PartialOrd
  289. {
  290. type Output = Ratio<T>;
  291. #[inline]
  292. fn neg(self) -> Ratio<T> { -&self }
  293. }
  294. impl<'a, T> Neg for &'a Ratio<T>
  295. where T: Clone + Integer + PartialOrd
  296. {
  297. type Output = Ratio<T>;
  298. #[inline]
  299. fn neg(self) -> Ratio<T> {
  300. Ratio::new_raw(-self.numer.clone(), self.denom.clone())
  301. }
  302. }
  303. /* Constants */
  304. impl<T: Clone + Integer + PartialOrd>
  305. Zero for Ratio<T> {
  306. #[inline]
  307. fn zero() -> Ratio<T> {
  308. Ratio::new_raw(Zero::zero(), One::one())
  309. }
  310. #[inline]
  311. fn is_zero(&self) -> bool {
  312. *self == Zero::zero()
  313. }
  314. }
  315. impl<T: Clone + Integer + PartialOrd>
  316. One for Ratio<T> {
  317. #[inline]
  318. fn one() -> Ratio<T> {
  319. Ratio::new_raw(One::one(), One::one())
  320. }
  321. }
  322. impl<T: Clone + Integer + PartialOrd>
  323. Num for Ratio<T> {}
  324. impl<T: Clone + Integer + PartialOrd>
  325. Signed for Ratio<T> {
  326. #[inline]
  327. fn abs(&self) -> Ratio<T> {
  328. if self.is_negative() { -self.clone() } else { self.clone() }
  329. }
  330. #[inline]
  331. fn abs_sub(&self, other: &Ratio<T>) -> Ratio<T> {
  332. if *self <= *other { Zero::zero() } else { self - other }
  333. }
  334. #[inline]
  335. fn signum(&self) -> Ratio<T> {
  336. if *self > Zero::zero() {
  337. One::one()
  338. } else if self.is_zero() {
  339. Zero::zero()
  340. } else {
  341. - ::one::<Ratio<T>>()
  342. }
  343. }
  344. #[inline]
  345. fn is_positive(&self) -> bool { *self > Zero::zero() }
  346. #[inline]
  347. fn is_negative(&self) -> bool { *self < Zero::zero() }
  348. }
  349. /* String conversions */
  350. impl<T: fmt::Show + Eq + One> fmt::Show for Ratio<T> {
  351. /// Renders as `numer/denom`. If denom=1, renders as numer.
  352. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  353. if self.denom == One::one() {
  354. write!(f, "{}", self.numer)
  355. } else {
  356. write!(f, "{}/{}", self.numer, self.denom)
  357. }
  358. }
  359. }
  360. impl<T: FromStr + Clone + Integer + PartialOrd>
  361. FromStr for Ratio<T> {
  362. /// Parses `numer/denom` or just `numer`.
  363. fn from_str(s: &str) -> Option<Ratio<T>> {
  364. let mut split = s.splitn(1, '/');
  365. let num = split.next().and_then(|n| FromStr::from_str(n));
  366. let den = split.next().or(Some("1")).and_then(|d| FromStr::from_str(d));
  367. match (num, den) {
  368. (Some(n), Some(d)) => Some(Ratio::new(n, d)),
  369. _ => None
  370. }
  371. }
  372. }
  373. impl<T: FromStrRadix + Clone + Integer + PartialOrd>
  374. FromStrRadix for Ratio<T> {
  375. /// Parses `numer/denom` where the numbers are in base `radix`.
  376. fn from_str_radix(s: &str, radix: uint) -> Option<Ratio<T>> {
  377. let split: Vec<&str> = s.splitn(1, '/').collect();
  378. if split.len() < 2 {
  379. None
  380. } else {
  381. let a_option: Option<T> = FromStrRadix::from_str_radix(
  382. split[0],
  383. radix);
  384. a_option.and_then(|a| {
  385. let b_option: Option<T> =
  386. FromStrRadix::from_str_radix(split[1], radix);
  387. b_option.and_then(|b| {
  388. Some(Ratio::new(a.clone(), b.clone()))
  389. })
  390. })
  391. }
  392. }
  393. }
  394. #[cfg(test)]
  395. mod test {
  396. use super::{Ratio, Rational, BigRational};
  397. use std::num::{FromPrimitive, Float};
  398. use std::str::FromStr;
  399. use std::hash::hash;
  400. use std::i32;
  401. use {Zero, One, Signed};
  402. pub const _0 : Rational = Ratio { numer: 0, denom: 1};
  403. pub const _1 : Rational = Ratio { numer: 1, denom: 1};
  404. pub const _2: Rational = Ratio { numer: 2, denom: 1};
  405. pub const _1_2: Rational = Ratio { numer: 1, denom: 2};
  406. pub const _3_2: Rational = Ratio { numer: 3, denom: 2};
  407. pub const _NEG1_2: Rational = Ratio { numer: -1, denom: 2};
  408. pub const _1_3: Rational = Ratio { numer: 1, denom: 3};
  409. pub const _NEG1_3: Rational = Ratio { numer: -1, denom: 3};
  410. pub const _2_3: Rational = Ratio { numer: 2, denom: 3};
  411. pub const _NEG2_3: Rational = Ratio { numer: -2, denom: 3};
  412. pub fn to_big(n: Rational) -> BigRational {
  413. Ratio::new(
  414. FromPrimitive::from_int(n.numer).unwrap(),
  415. FromPrimitive::from_int(n.denom).unwrap()
  416. )
  417. }
  418. #[test]
  419. fn test_test_constants() {
  420. // check our constants are what Ratio::new etc. would make.
  421. assert_eq!(_0, Zero::zero());
  422. assert_eq!(_1, One::one());
  423. assert_eq!(_2, Ratio::from_integer(2i));
  424. assert_eq!(_1_2, Ratio::new(1i,2i));
  425. assert_eq!(_3_2, Ratio::new(3i,2i));
  426. assert_eq!(_NEG1_2, Ratio::new(-1i,2i));
  427. }
  428. #[test]
  429. fn test_new_reduce() {
  430. let one22 = Ratio::new(2i,2);
  431. assert_eq!(one22, One::one());
  432. }
  433. #[test]
  434. #[should_fail]
  435. fn test_new_zero() {
  436. let _a = Ratio::new(1i,0);
  437. }
  438. #[test]
  439. fn test_cmp() {
  440. assert!(_0 == _0 && _1 == _1);
  441. assert!(_0 != _1 && _1 != _0);
  442. assert!(_0 < _1 && !(_1 < _0));
  443. assert!(_1 > _0 && !(_0 > _1));
  444. assert!(_0 <= _0 && _1 <= _1);
  445. assert!(_0 <= _1 && !(_1 <= _0));
  446. assert!(_0 >= _0 && _1 >= _1);
  447. assert!(_1 >= _0 && !(_0 >= _1));
  448. }
  449. #[test]
  450. fn test_to_integer() {
  451. assert_eq!(_0.to_integer(), 0);
  452. assert_eq!(_1.to_integer(), 1);
  453. assert_eq!(_2.to_integer(), 2);
  454. assert_eq!(_1_2.to_integer(), 0);
  455. assert_eq!(_3_2.to_integer(), 1);
  456. assert_eq!(_NEG1_2.to_integer(), 0);
  457. }
  458. #[test]
  459. fn test_numer() {
  460. assert_eq!(_0.numer(), &0);
  461. assert_eq!(_1.numer(), &1);
  462. assert_eq!(_2.numer(), &2);
  463. assert_eq!(_1_2.numer(), &1);
  464. assert_eq!(_3_2.numer(), &3);
  465. assert_eq!(_NEG1_2.numer(), &(-1));
  466. }
  467. #[test]
  468. fn test_denom() {
  469. assert_eq!(_0.denom(), &1);
  470. assert_eq!(_1.denom(), &1);
  471. assert_eq!(_2.denom(), &1);
  472. assert_eq!(_1_2.denom(), &2);
  473. assert_eq!(_3_2.denom(), &2);
  474. assert_eq!(_NEG1_2.denom(), &2);
  475. }
  476. #[test]
  477. fn test_is_integer() {
  478. assert!(_0.is_integer());
  479. assert!(_1.is_integer());
  480. assert!(_2.is_integer());
  481. assert!(!_1_2.is_integer());
  482. assert!(!_3_2.is_integer());
  483. assert!(!_NEG1_2.is_integer());
  484. }
  485. #[test]
  486. fn test_show() {
  487. assert_eq!(format!("{}", _2), "2".to_string());
  488. assert_eq!(format!("{}", _1_2), "1/2".to_string());
  489. assert_eq!(format!("{}", _0), "0".to_string());
  490. assert_eq!(format!("{}", Ratio::from_integer(-2i)), "-2".to_string());
  491. }
  492. mod arith {
  493. use super::{_0, _1, _2, _1_2, _3_2, _NEG1_2, to_big};
  494. use super::super::{Ratio, Rational};
  495. #[test]
  496. fn test_add() {
  497. fn test(a: Rational, b: Rational, c: Rational) {
  498. assert_eq!(a + b, c);
  499. assert_eq!(to_big(a) + to_big(b), to_big(c));
  500. }
  501. test(_1, _1_2, _3_2);
  502. test(_1, _1, _2);
  503. test(_1_2, _3_2, _2);
  504. test(_1_2, _NEG1_2, _0);
  505. }
  506. #[test]
  507. fn test_sub() {
  508. fn test(a: Rational, b: Rational, c: Rational) {
  509. assert_eq!(a - b, c);
  510. assert_eq!(to_big(a) - to_big(b), to_big(c))
  511. }
  512. test(_1, _1_2, _1_2);
  513. test(_3_2, _1_2, _1);
  514. test(_1, _NEG1_2, _3_2);
  515. }
  516. #[test]
  517. fn test_mul() {
  518. fn test(a: Rational, b: Rational, c: Rational) {
  519. assert_eq!(a * b, c);
  520. assert_eq!(to_big(a) * to_big(b), to_big(c))
  521. }
  522. test(_1, _1_2, _1_2);
  523. test(_1_2, _3_2, Ratio::new(3i,4i));
  524. test(_1_2, _NEG1_2, Ratio::new(-1i, 4i));
  525. }
  526. #[test]
  527. fn test_div() {
  528. fn test(a: Rational, b: Rational, c: Rational) {
  529. assert_eq!(a / b, c);
  530. assert_eq!(to_big(a) / to_big(b), to_big(c))
  531. }
  532. test(_1, _1_2, _2);
  533. test(_3_2, _1_2, _1 + _2);
  534. test(_1, _NEG1_2, _NEG1_2 + _NEG1_2 + _NEG1_2 + _NEG1_2);
  535. }
  536. #[test]
  537. fn test_rem() {
  538. fn test(a: Rational, b: Rational, c: Rational) {
  539. assert_eq!(a % b, c);
  540. assert_eq!(to_big(a) % to_big(b), to_big(c))
  541. }
  542. test(_3_2, _1, _1_2);
  543. test(_2, _NEG1_2, _0);
  544. test(_1_2, _2, _1_2);
  545. }
  546. #[test]
  547. fn test_neg() {
  548. fn test(a: Rational, b: Rational) {
  549. assert_eq!(-a, b);
  550. assert_eq!(-to_big(a), to_big(b))
  551. }
  552. test(_0, _0);
  553. test(_1_2, _NEG1_2);
  554. test(-_1, _1);
  555. }
  556. #[test]
  557. fn test_zero() {
  558. assert_eq!(_0 + _0, _0);
  559. assert_eq!(_0 * _0, _0);
  560. assert_eq!(_0 * _1, _0);
  561. assert_eq!(_0 / _NEG1_2, _0);
  562. assert_eq!(_0 - _0, _0);
  563. }
  564. #[test]
  565. #[should_fail]
  566. fn test_div_0() {
  567. let _a = _1 / _0;
  568. }
  569. }
  570. #[test]
  571. fn test_round() {
  572. assert_eq!(_1_3.ceil(), _1);
  573. assert_eq!(_1_3.floor(), _0);
  574. assert_eq!(_1_3.round(), _0);
  575. assert_eq!(_1_3.trunc(), _0);
  576. assert_eq!(_NEG1_3.ceil(), _0);
  577. assert_eq!(_NEG1_3.floor(), -_1);
  578. assert_eq!(_NEG1_3.round(), _0);
  579. assert_eq!(_NEG1_3.trunc(), _0);
  580. assert_eq!(_2_3.ceil(), _1);
  581. assert_eq!(_2_3.floor(), _0);
  582. assert_eq!(_2_3.round(), _1);
  583. assert_eq!(_2_3.trunc(), _0);
  584. assert_eq!(_NEG2_3.ceil(), _0);
  585. assert_eq!(_NEG2_3.floor(), -_1);
  586. assert_eq!(_NEG2_3.round(), -_1);
  587. assert_eq!(_NEG2_3.trunc(), _0);
  588. assert_eq!(_1_2.ceil(), _1);
  589. assert_eq!(_1_2.floor(), _0);
  590. assert_eq!(_1_2.round(), _1);
  591. assert_eq!(_1_2.trunc(), _0);
  592. assert_eq!(_NEG1_2.ceil(), _0);
  593. assert_eq!(_NEG1_2.floor(), -_1);
  594. assert_eq!(_NEG1_2.round(), -_1);
  595. assert_eq!(_NEG1_2.trunc(), _0);
  596. assert_eq!(_1.ceil(), _1);
  597. assert_eq!(_1.floor(), _1);
  598. assert_eq!(_1.round(), _1);
  599. assert_eq!(_1.trunc(), _1);
  600. // Overflow checks
  601. let _neg1 = Ratio::from_integer(-1);
  602. let _large_rat1 = Ratio::new(i32::MAX, i32::MAX-1);
  603. let _large_rat2 = Ratio::new(i32::MAX-1, i32::MAX);
  604. let _large_rat3 = Ratio::new(i32::MIN+2, i32::MIN+1);
  605. let _large_rat4 = Ratio::new(i32::MIN+1, i32::MIN+2);
  606. let _large_rat5 = Ratio::new(i32::MIN+2, i32::MAX);
  607. let _large_rat6 = Ratio::new(i32::MAX, i32::MIN+2);
  608. let _large_rat7 = Ratio::new(1, i32::MIN+1);
  609. let _large_rat8 = Ratio::new(1, i32::MAX);
  610. assert_eq!(_large_rat1.round(), One::one());
  611. assert_eq!(_large_rat2.round(), One::one());
  612. assert_eq!(_large_rat3.round(), One::one());
  613. assert_eq!(_large_rat4.round(), One::one());
  614. assert_eq!(_large_rat5.round(), _neg1);
  615. assert_eq!(_large_rat6.round(), _neg1);
  616. assert_eq!(_large_rat7.round(), Zero::zero());
  617. assert_eq!(_large_rat8.round(), Zero::zero());
  618. }
  619. #[test]
  620. fn test_fract() {
  621. assert_eq!(_1.fract(), _0);
  622. assert_eq!(_NEG1_2.fract(), _NEG1_2);
  623. assert_eq!(_1_2.fract(), _1_2);
  624. assert_eq!(_3_2.fract(), _1_2);
  625. }
  626. #[test]
  627. fn test_recip() {
  628. assert_eq!(_1 * _1.recip(), _1);
  629. assert_eq!(_2 * _2.recip(), _1);
  630. assert_eq!(_1_2 * _1_2.recip(), _1);
  631. assert_eq!(_3_2 * _3_2.recip(), _1);
  632. assert_eq!(_NEG1_2 * _NEG1_2.recip(), _1);
  633. }
  634. #[test]
  635. fn test_to_from_str() {
  636. fn test(r: Rational, s: String) {
  637. assert_eq!(FromStr::from_str(s[]), Some(r));
  638. assert_eq!(r.to_string(), s);
  639. }
  640. test(_1, "1".to_string());
  641. test(_0, "0".to_string());
  642. test(_1_2, "1/2".to_string());
  643. test(_3_2, "3/2".to_string());
  644. test(_2, "2".to_string());
  645. test(_NEG1_2, "-1/2".to_string());
  646. }
  647. #[test]
  648. fn test_from_str_fail() {
  649. fn test(s: &str) {
  650. let rational: Option<Rational> = FromStr::from_str(s);
  651. assert_eq!(rational, None);
  652. }
  653. let xs = ["0 /1", "abc", "", "1/", "--1/2","3/2/1"];
  654. for &s in xs.iter() {
  655. test(s);
  656. }
  657. }
  658. #[test]
  659. fn test_from_float() {
  660. fn test<T: Float>(given: T, (numer, denom): (&str, &str)) {
  661. let ratio: BigRational = Ratio::from_float(given).unwrap();
  662. assert_eq!(ratio, Ratio::new(
  663. FromStr::from_str(numer).unwrap(),
  664. FromStr::from_str(denom).unwrap()));
  665. }
  666. // f32
  667. test(3.14159265359f32, ("13176795", "4194304"));
  668. test(2f32.powf(100.), ("1267650600228229401496703205376", "1"));
  669. test(-2f32.powf(100.), ("-1267650600228229401496703205376", "1"));
  670. test(1.0 / 2f32.powf(100.), ("1", "1267650600228229401496703205376"));
  671. test(684729.48391f32, ("1369459", "2"));
  672. test(-8573.5918555f32, ("-4389679", "512"));
  673. // f64
  674. test(3.14159265359f64, ("3537118876014453", "1125899906842624"));
  675. test(2f64.powf(100.), ("1267650600228229401496703205376", "1"));
  676. test(-2f64.powf(100.), ("-1267650600228229401496703205376", "1"));
  677. test(684729.48391f64, ("367611342500051", "536870912"));
  678. test(-8573.5918555f64, ("-4713381968463931", "549755813888"));
  679. test(1.0 / 2f64.powf(100.), ("1", "1267650600228229401496703205376"));
  680. }
  681. #[test]
  682. fn test_from_float_fail() {
  683. use std::{f32, f64};
  684. assert_eq!(Ratio::from_float(f32::NAN), None);
  685. assert_eq!(Ratio::from_float(f32::INFINITY), None);
  686. assert_eq!(Ratio::from_float(f32::NEG_INFINITY), None);
  687. assert_eq!(Ratio::from_float(f64::NAN), None);
  688. assert_eq!(Ratio::from_float(f64::INFINITY), None);
  689. assert_eq!(Ratio::from_float(f64::NEG_INFINITY), None);
  690. }
  691. #[test]
  692. fn test_signed() {
  693. assert_eq!(_NEG1_2.abs(), _1_2);
  694. assert_eq!(_3_2.abs_sub(&_1_2), _1);
  695. assert_eq!(_1_2.abs_sub(&_3_2), Zero::zero());
  696. assert_eq!(_1_2.signum(), One::one());
  697. assert_eq!(_NEG1_2.signum(), - ::one::<Ratio<int>>());
  698. assert!(_NEG1_2.is_negative());
  699. assert!(! _NEG1_2.is_positive());
  700. assert!(! _1_2.is_negative());
  701. }
  702. #[test]
  703. fn test_hash() {
  704. assert!(hash(&_0) != hash(&_1));
  705. assert!(hash(&_0) != hash(&_3_2));
  706. }
  707. }