rational.rs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  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::error::Error;
  14. use std::fmt;
  15. use std::ops::{Add, Div, Mul, Neg, Rem, Sub};
  16. use std::str::FromStr;
  17. use traits::{FromPrimitive, Float};
  18. use bigint::{BigInt, BigUint, Sign};
  19. use {Num, Signed, Zero, One};
  20. /// Represents the ratio between 2 numbers.
  21. #[derive(Copy, Clone, Hash, RustcEncodable, RustcDecodable, Debug)]
  22. #[allow(missing_docs)]
  23. pub struct Ratio<T> {
  24. numer: T,
  25. denom: T
  26. }
  27. /// Alias for a `Ratio` of machine-sized integers.
  28. pub type Rational = Ratio<isize>;
  29. pub type Rational32 = Ratio<i32>;
  30. pub type Rational64 = Ratio<i64>;
  31. /// Alias for arbitrary precision rationals.
  32. pub type BigRational = Ratio<BigInt>;
  33. impl<T: Clone + Integer + PartialOrd> 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 < T::zero() {
  85. self.numer = T::zero() - self.numer.clone();
  86. self.denom = T::zero() - 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 zero: Ratio<T> = Zero::zero();
  124. let one: T = One::one();
  125. let two: T = one.clone() + one.clone();
  126. // Find unsigned fractional part of rational number
  127. let mut fractional = self.fract();
  128. if fractional < zero { fractional = zero - fractional };
  129. // The algorithm compares the unsigned fractional part with 1/2, that
  130. // is, a/b >= 1/2, or a >= b/2. For odd denominators, we use
  131. // a >= (b/2)+1. This avoids overflow issues.
  132. let half_or_larger = if fractional.denom().is_even() {
  133. *fractional.numer() >= fractional.denom().clone() / two.clone()
  134. } else {
  135. *fractional.numer() >= (fractional.denom().clone() / two.clone()) + one.clone()
  136. };
  137. if half_or_larger {
  138. let one: Ratio<T> = One::one();
  139. if *self >= Zero::zero() {
  140. self.trunc() + one
  141. } else {
  142. self.trunc() - one
  143. }
  144. } else {
  145. self.trunc()
  146. }
  147. }
  148. /// Rounds towards zero.
  149. #[inline]
  150. pub fn trunc(&self) -> Ratio<T> {
  151. Ratio::from_integer(self.numer.clone() / self.denom.clone())
  152. }
  153. /// Returns the fractional part of a number.
  154. #[inline]
  155. pub fn fract(&self) -> Ratio<T> {
  156. Ratio::new_raw(self.numer.clone() % self.denom.clone(), self.denom.clone())
  157. }
  158. }
  159. impl Ratio<BigInt> {
  160. /// Converts a float into a rational number.
  161. pub fn from_float<T: Float>(f: T) -> Option<BigRational> {
  162. if !f.is_finite() {
  163. return None;
  164. }
  165. let (mantissa, exponent, sign) = f.integer_decode();
  166. let bigint_sign = if sign == 1 { Sign::Plus } else { Sign::Minus };
  167. if exponent < 0 {
  168. let one: BigInt = One::one();
  169. let denom: BigInt = one << ((-exponent) as usize);
  170. let numer: BigUint = FromPrimitive::from_u64(mantissa).unwrap();
  171. Some(Ratio::new(BigInt::from_biguint(bigint_sign, numer), denom))
  172. } else {
  173. let mut numer: BigUint = FromPrimitive::from_u64(mantissa).unwrap();
  174. numer = numer << (exponent as usize);
  175. Some(Ratio::from_integer(BigInt::from_biguint(bigint_sign, numer)))
  176. }
  177. }
  178. }
  179. /* Comparisons */
  180. // comparing a/b and c/d is the same as comparing a*d and b*c, so we
  181. // abstract that pattern. The following macro takes a trait and either
  182. // a comma-separated list of "method name -> return value" or just
  183. // "method name" (return value is bool in that case)
  184. macro_rules! cmp_impl {
  185. (impl $imp:ident, $($method:ident),+) => {
  186. cmp_impl!(impl $imp, $($method -> bool),+);
  187. };
  188. // return something other than a Ratio<T>
  189. (impl $imp:ident, $($method:ident -> $res:ty),*) => {
  190. impl<T> $imp for Ratio<T> where
  191. T: Clone + Mul<T, Output = T> + $imp
  192. {
  193. $(
  194. #[inline]
  195. fn $method(&self, other: &Ratio<T>) -> $res {
  196. (self.numer.clone() * other.denom.clone()). $method (&(self.denom.clone()*other.numer.clone()))
  197. }
  198. )*
  199. }
  200. };
  201. }
  202. cmp_impl!(impl PartialEq, eq, ne);
  203. cmp_impl!(impl PartialOrd, lt -> bool, gt -> bool, le -> bool, ge -> bool,
  204. partial_cmp -> Option<cmp::Ordering>);
  205. cmp_impl!(impl Eq, );
  206. cmp_impl!(impl Ord, cmp -> cmp::Ordering);
  207. macro_rules! forward_val_val_binop {
  208. (impl $imp:ident, $method:ident) => {
  209. impl<T: Clone + Integer + PartialOrd> $imp<Ratio<T>> for Ratio<T> {
  210. type Output = Ratio<T>;
  211. #[inline]
  212. fn $method(self, other: Ratio<T>) -> Ratio<T> {
  213. (&self).$method(&other)
  214. }
  215. }
  216. }
  217. }
  218. macro_rules! forward_ref_val_binop {
  219. (impl $imp:ident, $method:ident) => {
  220. impl<'a, T> $imp<Ratio<T>> for &'a Ratio<T> where
  221. T: Clone + Integer + PartialOrd
  222. {
  223. type Output = Ratio<T>;
  224. #[inline]
  225. fn $method(self, other: Ratio<T>) -> Ratio<T> {
  226. self.$method(&other)
  227. }
  228. }
  229. }
  230. }
  231. macro_rules! forward_val_ref_binop {
  232. (impl $imp:ident, $method:ident) => {
  233. impl<'a, T> $imp<&'a Ratio<T>> for Ratio<T> where
  234. T: Clone + Integer + PartialOrd
  235. {
  236. type Output = Ratio<T>;
  237. #[inline]
  238. fn $method(self, other: &Ratio<T>) -> Ratio<T> {
  239. (&self).$method(other)
  240. }
  241. }
  242. }
  243. }
  244. macro_rules! forward_all_binop {
  245. (impl $imp:ident, $method:ident) => {
  246. forward_val_val_binop!(impl $imp, $method);
  247. forward_ref_val_binop!(impl $imp, $method);
  248. forward_val_ref_binop!(impl $imp, $method);
  249. };
  250. }
  251. /* Arithmetic */
  252. forward_all_binop!(impl Mul, mul);
  253. // a/b * c/d = (a*c)/(b*d)
  254. impl<'a, 'b, T> Mul<&'b Ratio<T>> for &'a Ratio<T>
  255. where T: Clone + Integer + PartialOrd
  256. {
  257. type Output = Ratio<T>;
  258. #[inline]
  259. fn mul(self, rhs: &Ratio<T>) -> Ratio<T> {
  260. Ratio::new(self.numer.clone() * rhs.numer.clone(), self.denom.clone() * rhs.denom.clone())
  261. }
  262. }
  263. forward_all_binop!(impl Div, div);
  264. // (a/b) / (c/d) = (a*d)/(b*c)
  265. impl<'a, 'b, T> Div<&'b Ratio<T>> for &'a Ratio<T>
  266. where T: Clone + Integer + PartialOrd
  267. {
  268. type Output = Ratio<T>;
  269. #[inline]
  270. fn div(self, rhs: &Ratio<T>) -> Ratio<T> {
  271. Ratio::new(self.numer.clone() * rhs.denom.clone(), self.denom.clone() * rhs.numer.clone())
  272. }
  273. }
  274. // Abstracts the a/b `op` c/d = (a*d `op` b*d) / (b*d) pattern
  275. macro_rules! arith_impl {
  276. (impl $imp:ident, $method:ident) => {
  277. forward_all_binop!(impl $imp, $method);
  278. impl<'a, 'b, T: Clone + Integer + PartialOrd>
  279. $imp<&'b Ratio<T>> for &'a Ratio<T> {
  280. type Output = Ratio<T>;
  281. #[inline]
  282. fn $method(self, rhs: &Ratio<T>) -> Ratio<T> {
  283. Ratio::new((self.numer.clone() * rhs.denom.clone()).$method(self.denom.clone() * rhs.numer.clone()),
  284. self.denom.clone() * rhs.denom.clone())
  285. }
  286. }
  287. }
  288. }
  289. // a/b + c/d = (a*d + b*c)/(b*d)
  290. arith_impl!(impl Add, add);
  291. // a/b - c/d = (a*d - b*c)/(b*d)
  292. arith_impl!(impl Sub, sub);
  293. // a/b % c/d = (a*d % b*c)/(b*d)
  294. arith_impl!(impl Rem, rem);
  295. impl<T> Neg for Ratio<T>
  296. where T: Clone + Integer + PartialOrd + Neg<Output = T>
  297. {
  298. type Output = Ratio<T>;
  299. #[inline]
  300. fn neg(self) -> Ratio<T> { -&self }
  301. }
  302. impl<'a, T> Neg for &'a Ratio<T>
  303. where T: Clone + Integer + PartialOrd + Neg<Output = T>
  304. {
  305. type Output = Ratio<T>;
  306. #[inline]
  307. fn neg(self) -> Ratio<T> {
  308. Ratio::new_raw(-self.numer.clone(), self.denom.clone())
  309. }
  310. }
  311. /* Constants */
  312. impl<T: Clone + Integer + PartialOrd>
  313. Zero for Ratio<T> {
  314. #[inline]
  315. fn zero() -> Ratio<T> {
  316. Ratio::new_raw(Zero::zero(), One::one())
  317. }
  318. #[inline]
  319. fn is_zero(&self) -> bool {
  320. *self == Zero::zero()
  321. }
  322. }
  323. impl<T: Clone + Integer + PartialOrd>
  324. One for Ratio<T> {
  325. #[inline]
  326. fn one() -> Ratio<T> {
  327. Ratio::new_raw(One::one(), One::one())
  328. }
  329. }
  330. impl<T: Clone + Integer + PartialOrd> Num for Ratio<T> {
  331. type FromStrRadixErr = ParseRatioError;
  332. /// Parses `numer/denom` where the numbers are in base `radix`.
  333. fn from_str_radix(s: &str, radix: u32) -> Result<Ratio<T>, ParseRatioError> {
  334. let split: Vec<&str> = s.splitn(2, '/').collect();
  335. if split.len() < 2 {
  336. Err(ParseRatioError)
  337. } else {
  338. let a_result: Result<T, _> = T::from_str_radix(
  339. split[0],
  340. radix).map_err(|_| ParseRatioError);
  341. a_result.and_then(|a| {
  342. let b_result: Result<T, _> =
  343. T::from_str_radix(split[1], radix).map_err(|_| ParseRatioError);
  344. b_result.and_then(|b| {
  345. Ok(Ratio::new(a.clone(), b.clone()))
  346. })
  347. })
  348. }
  349. }
  350. }
  351. impl<T: Clone + Integer + PartialOrd + Signed> Signed for Ratio<T> {
  352. #[inline]
  353. fn abs(&self) -> Ratio<T> {
  354. if self.is_negative() { -self.clone() } else { self.clone() }
  355. }
  356. #[inline]
  357. fn abs_sub(&self, other: &Ratio<T>) -> Ratio<T> {
  358. if *self <= *other { Zero::zero() } else { self - other }
  359. }
  360. #[inline]
  361. fn signum(&self) -> Ratio<T> {
  362. if *self > Zero::zero() {
  363. One::one()
  364. } else if self.is_zero() {
  365. Zero::zero()
  366. } else {
  367. - ::one::<Ratio<T>>()
  368. }
  369. }
  370. #[inline]
  371. fn is_positive(&self) -> bool { *self > Zero::zero() }
  372. #[inline]
  373. fn is_negative(&self) -> bool { *self < Zero::zero() }
  374. }
  375. /* String conversions */
  376. impl<T> fmt::Display for Ratio<T> where
  377. T: fmt::Display + Eq + One
  378. {
  379. /// Renders as `numer/denom`. If denom=1, renders as numer.
  380. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  381. if self.denom == One::one() {
  382. write!(f, "{}", self.numer)
  383. } else {
  384. write!(f, "{}/{}", self.numer, self.denom)
  385. }
  386. }
  387. }
  388. impl<T: FromStr + Clone + Integer + PartialOrd> FromStr for Ratio<T> {
  389. type Err = ParseRatioError;
  390. /// Parses `numer/denom` or just `numer`.
  391. fn from_str(s: &str) -> Result<Ratio<T>, ParseRatioError> {
  392. let mut split = s.splitn(2, '/');
  393. let n = try!(split.next().ok_or(ParseRatioError));
  394. let num = try!(FromStr::from_str(n).map_err(|_| ParseRatioError));
  395. let d = split.next().unwrap_or("1");
  396. let den = try!(FromStr::from_str(d).map_err(|_| ParseRatioError));
  397. Ok(Ratio::new(num, den))
  398. }
  399. }
  400. // FIXME: Bubble up specific errors
  401. #[derive(Copy, Clone, Debug, PartialEq)]
  402. pub struct ParseRatioError;
  403. impl fmt::Display for ParseRatioError {
  404. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  405. "failed to parse provided string".fmt(f)
  406. }
  407. }
  408. impl Error for ParseRatioError {
  409. fn description(&self) -> &str { "failed to parse bigint/biguint" }
  410. }
  411. #[cfg(test)]
  412. mod test {
  413. use super::{Ratio, Rational, BigRational};
  414. use std::str::FromStr;
  415. use std::i32;
  416. use {Zero, One, Signed, FromPrimitive, Float};
  417. pub const _0 : Rational = Ratio { numer: 0, denom: 1};
  418. pub const _1 : Rational = Ratio { numer: 1, denom: 1};
  419. pub const _2: Rational = Ratio { numer: 2, denom: 1};
  420. pub const _1_2: Rational = Ratio { numer: 1, denom: 2};
  421. pub const _3_2: Rational = Ratio { numer: 3, denom: 2};
  422. pub const _NEG1_2: Rational = Ratio { numer: -1, denom: 2};
  423. pub const _1_3: Rational = Ratio { numer: 1, denom: 3};
  424. pub const _NEG1_3: Rational = Ratio { numer: -1, denom: 3};
  425. pub const _2_3: Rational = Ratio { numer: 2, denom: 3};
  426. pub const _NEG2_3: Rational = Ratio { numer: -2, denom: 3};
  427. pub fn to_big(n: Rational) -> BigRational {
  428. Ratio::new(
  429. FromPrimitive::from_isize(n.numer).unwrap(),
  430. FromPrimitive::from_isize(n.denom).unwrap()
  431. )
  432. }
  433. #[test]
  434. fn test_test_constants() {
  435. // check our constants are what Ratio::new etc. would make.
  436. assert_eq!(_0, Zero::zero());
  437. assert_eq!(_1, One::one());
  438. assert_eq!(_2, Ratio::from_integer(2));
  439. assert_eq!(_1_2, Ratio::new(1,2));
  440. assert_eq!(_3_2, Ratio::new(3,2));
  441. assert_eq!(_NEG1_2, Ratio::new(-1,2));
  442. }
  443. #[test]
  444. fn test_new_reduce() {
  445. let one22 = Ratio::new(2,2);
  446. assert_eq!(one22, One::one());
  447. }
  448. #[test]
  449. #[should_panic]
  450. fn test_new_zero() {
  451. let _a = Ratio::new(1,0);
  452. }
  453. #[test]
  454. fn test_cmp() {
  455. assert!(_0 == _0 && _1 == _1);
  456. assert!(_0 != _1 && _1 != _0);
  457. assert!(_0 < _1 && !(_1 < _0));
  458. assert!(_1 > _0 && !(_0 > _1));
  459. assert!(_0 <= _0 && _1 <= _1);
  460. assert!(_0 <= _1 && !(_1 <= _0));
  461. assert!(_0 >= _0 && _1 >= _1);
  462. assert!(_1 >= _0 && !(_0 >= _1));
  463. }
  464. #[test]
  465. fn test_to_integer() {
  466. assert_eq!(_0.to_integer(), 0);
  467. assert_eq!(_1.to_integer(), 1);
  468. assert_eq!(_2.to_integer(), 2);
  469. assert_eq!(_1_2.to_integer(), 0);
  470. assert_eq!(_3_2.to_integer(), 1);
  471. assert_eq!(_NEG1_2.to_integer(), 0);
  472. }
  473. #[test]
  474. fn test_numer() {
  475. assert_eq!(_0.numer(), &0);
  476. assert_eq!(_1.numer(), &1);
  477. assert_eq!(_2.numer(), &2);
  478. assert_eq!(_1_2.numer(), &1);
  479. assert_eq!(_3_2.numer(), &3);
  480. assert_eq!(_NEG1_2.numer(), &(-1));
  481. }
  482. #[test]
  483. fn test_denom() {
  484. assert_eq!(_0.denom(), &1);
  485. assert_eq!(_1.denom(), &1);
  486. assert_eq!(_2.denom(), &1);
  487. assert_eq!(_1_2.denom(), &2);
  488. assert_eq!(_3_2.denom(), &2);
  489. assert_eq!(_NEG1_2.denom(), &2);
  490. }
  491. #[test]
  492. fn test_is_integer() {
  493. assert!(_0.is_integer());
  494. assert!(_1.is_integer());
  495. assert!(_2.is_integer());
  496. assert!(!_1_2.is_integer());
  497. assert!(!_3_2.is_integer());
  498. assert!(!_NEG1_2.is_integer());
  499. }
  500. #[test]
  501. fn test_show() {
  502. assert_eq!(format!("{}", _2), "2".to_string());
  503. assert_eq!(format!("{}", _1_2), "1/2".to_string());
  504. assert_eq!(format!("{}", _0), "0".to_string());
  505. assert_eq!(format!("{}", Ratio::from_integer(-2)), "-2".to_string());
  506. }
  507. mod arith {
  508. use super::{_0, _1, _2, _1_2, _3_2, _NEG1_2, to_big};
  509. use super::super::{Ratio, Rational};
  510. #[test]
  511. fn test_add() {
  512. fn test(a: Rational, b: Rational, c: Rational) {
  513. assert_eq!(a + b, c);
  514. assert_eq!(to_big(a) + to_big(b), to_big(c));
  515. }
  516. test(_1, _1_2, _3_2);
  517. test(_1, _1, _2);
  518. test(_1_2, _3_2, _2);
  519. test(_1_2, _NEG1_2, _0);
  520. }
  521. #[test]
  522. fn test_sub() {
  523. fn test(a: Rational, b: Rational, c: Rational) {
  524. assert_eq!(a - b, c);
  525. assert_eq!(to_big(a) - to_big(b), to_big(c))
  526. }
  527. test(_1, _1_2, _1_2);
  528. test(_3_2, _1_2, _1);
  529. test(_1, _NEG1_2, _3_2);
  530. }
  531. #[test]
  532. fn test_mul() {
  533. fn test(a: Rational, b: Rational, c: Rational) {
  534. assert_eq!(a * b, c);
  535. assert_eq!(to_big(a) * to_big(b), to_big(c))
  536. }
  537. test(_1, _1_2, _1_2);
  538. test(_1_2, _3_2, Ratio::new(3,4));
  539. test(_1_2, _NEG1_2, Ratio::new(-1, 4));
  540. }
  541. #[test]
  542. fn test_div() {
  543. fn test(a: Rational, b: Rational, c: Rational) {
  544. assert_eq!(a / b, c);
  545. assert_eq!(to_big(a) / to_big(b), to_big(c))
  546. }
  547. test(_1, _1_2, _2);
  548. test(_3_2, _1_2, _1 + _2);
  549. test(_1, _NEG1_2, _NEG1_2 + _NEG1_2 + _NEG1_2 + _NEG1_2);
  550. }
  551. #[test]
  552. fn test_rem() {
  553. fn test(a: Rational, b: Rational, c: Rational) {
  554. assert_eq!(a % b, c);
  555. assert_eq!(to_big(a) % to_big(b), to_big(c))
  556. }
  557. test(_3_2, _1, _1_2);
  558. test(_2, _NEG1_2, _0);
  559. test(_1_2, _2, _1_2);
  560. }
  561. #[test]
  562. fn test_neg() {
  563. fn test(a: Rational, b: Rational) {
  564. assert_eq!(-a, b);
  565. assert_eq!(-to_big(a), to_big(b))
  566. }
  567. test(_0, _0);
  568. test(_1_2, _NEG1_2);
  569. test(-_1, _1);
  570. }
  571. #[test]
  572. fn test_zero() {
  573. assert_eq!(_0 + _0, _0);
  574. assert_eq!(_0 * _0, _0);
  575. assert_eq!(_0 * _1, _0);
  576. assert_eq!(_0 / _NEG1_2, _0);
  577. assert_eq!(_0 - _0, _0);
  578. }
  579. #[test]
  580. #[should_panic]
  581. fn test_div_0() {
  582. let _a = _1 / _0;
  583. }
  584. }
  585. #[test]
  586. fn test_round() {
  587. assert_eq!(_1_3.ceil(), _1);
  588. assert_eq!(_1_3.floor(), _0);
  589. assert_eq!(_1_3.round(), _0);
  590. assert_eq!(_1_3.trunc(), _0);
  591. assert_eq!(_NEG1_3.ceil(), _0);
  592. assert_eq!(_NEG1_3.floor(), -_1);
  593. assert_eq!(_NEG1_3.round(), _0);
  594. assert_eq!(_NEG1_3.trunc(), _0);
  595. assert_eq!(_2_3.ceil(), _1);
  596. assert_eq!(_2_3.floor(), _0);
  597. assert_eq!(_2_3.round(), _1);
  598. assert_eq!(_2_3.trunc(), _0);
  599. assert_eq!(_NEG2_3.ceil(), _0);
  600. assert_eq!(_NEG2_3.floor(), -_1);
  601. assert_eq!(_NEG2_3.round(), -_1);
  602. assert_eq!(_NEG2_3.trunc(), _0);
  603. assert_eq!(_1_2.ceil(), _1);
  604. assert_eq!(_1_2.floor(), _0);
  605. assert_eq!(_1_2.round(), _1);
  606. assert_eq!(_1_2.trunc(), _0);
  607. assert_eq!(_NEG1_2.ceil(), _0);
  608. assert_eq!(_NEG1_2.floor(), -_1);
  609. assert_eq!(_NEG1_2.round(), -_1);
  610. assert_eq!(_NEG1_2.trunc(), _0);
  611. assert_eq!(_1.ceil(), _1);
  612. assert_eq!(_1.floor(), _1);
  613. assert_eq!(_1.round(), _1);
  614. assert_eq!(_1.trunc(), _1);
  615. // Overflow checks
  616. let _neg1 = Ratio::from_integer(-1);
  617. let _large_rat1 = Ratio::new(i32::MAX, i32::MAX-1);
  618. let _large_rat2 = Ratio::new(i32::MAX-1, i32::MAX);
  619. let _large_rat3 = Ratio::new(i32::MIN+2, i32::MIN+1);
  620. let _large_rat4 = Ratio::new(i32::MIN+1, i32::MIN+2);
  621. let _large_rat5 = Ratio::new(i32::MIN+2, i32::MAX);
  622. let _large_rat6 = Ratio::new(i32::MAX, i32::MIN+2);
  623. let _large_rat7 = Ratio::new(1, i32::MIN+1);
  624. let _large_rat8 = Ratio::new(1, i32::MAX);
  625. assert_eq!(_large_rat1.round(), One::one());
  626. assert_eq!(_large_rat2.round(), One::one());
  627. assert_eq!(_large_rat3.round(), One::one());
  628. assert_eq!(_large_rat4.round(), One::one());
  629. assert_eq!(_large_rat5.round(), _neg1);
  630. assert_eq!(_large_rat6.round(), _neg1);
  631. assert_eq!(_large_rat7.round(), Zero::zero());
  632. assert_eq!(_large_rat8.round(), Zero::zero());
  633. }
  634. #[test]
  635. fn test_fract() {
  636. assert_eq!(_1.fract(), _0);
  637. assert_eq!(_NEG1_2.fract(), _NEG1_2);
  638. assert_eq!(_1_2.fract(), _1_2);
  639. assert_eq!(_3_2.fract(), _1_2);
  640. }
  641. #[test]
  642. fn test_recip() {
  643. assert_eq!(_1 * _1.recip(), _1);
  644. assert_eq!(_2 * _2.recip(), _1);
  645. assert_eq!(_1_2 * _1_2.recip(), _1);
  646. assert_eq!(_3_2 * _3_2.recip(), _1);
  647. assert_eq!(_NEG1_2 * _NEG1_2.recip(), _1);
  648. }
  649. #[test]
  650. fn test_to_from_str() {
  651. fn test(r: Rational, s: String) {
  652. assert_eq!(FromStr::from_str(&s), Ok(r));
  653. assert_eq!(r.to_string(), s);
  654. }
  655. test(_1, "1".to_string());
  656. test(_0, "0".to_string());
  657. test(_1_2, "1/2".to_string());
  658. test(_3_2, "3/2".to_string());
  659. test(_2, "2".to_string());
  660. test(_NEG1_2, "-1/2".to_string());
  661. }
  662. #[test]
  663. fn test_from_str_fail() {
  664. fn test(s: &str) {
  665. let rational: Result<Rational, _> = FromStr::from_str(s);
  666. assert!(rational.is_err());
  667. }
  668. let xs = ["0 /1", "abc", "", "1/", "--1/2","3/2/1"];
  669. for &s in xs.iter() {
  670. test(s);
  671. }
  672. }
  673. #[test]
  674. fn test_from_float() {
  675. fn test<T: Float>(given: T, (numer, denom): (&str, &str)) {
  676. let ratio: BigRational = Ratio::from_float(given).unwrap();
  677. assert_eq!(ratio, Ratio::new(
  678. FromStr::from_str(numer).unwrap(),
  679. FromStr::from_str(denom).unwrap()));
  680. }
  681. // f32
  682. test(3.14159265359f32, ("13176795", "4194304"));
  683. test(2f32.powf(100.), ("1267650600228229401496703205376", "1"));
  684. test(-2f32.powf(100.), ("-1267650600228229401496703205376", "1"));
  685. test(1.0 / 2f32.powf(100.), ("1", "1267650600228229401496703205376"));
  686. test(684729.48391f32, ("1369459", "2"));
  687. test(-8573.5918555f32, ("-4389679", "512"));
  688. // f64
  689. test(3.14159265359f64, ("3537118876014453", "1125899906842624"));
  690. test(2f64.powf(100.), ("1267650600228229401496703205376", "1"));
  691. test(-2f64.powf(100.), ("-1267650600228229401496703205376", "1"));
  692. test(684729.48391f64, ("367611342500051", "536870912"));
  693. test(-8573.5918555f64, ("-4713381968463931", "549755813888"));
  694. test(1.0 / 2f64.powf(100.), ("1", "1267650600228229401496703205376"));
  695. }
  696. #[test]
  697. fn test_from_float_fail() {
  698. use std::{f32, f64};
  699. assert_eq!(Ratio::from_float(f32::NAN), None);
  700. assert_eq!(Ratio::from_float(f32::INFINITY), None);
  701. assert_eq!(Ratio::from_float(f32::NEG_INFINITY), None);
  702. assert_eq!(Ratio::from_float(f64::NAN), None);
  703. assert_eq!(Ratio::from_float(f64::INFINITY), None);
  704. assert_eq!(Ratio::from_float(f64::NEG_INFINITY), None);
  705. }
  706. #[test]
  707. fn test_signed() {
  708. assert_eq!(_NEG1_2.abs(), _1_2);
  709. assert_eq!(_3_2.abs_sub(&_1_2), _1);
  710. assert_eq!(_1_2.abs_sub(&_3_2), Zero::zero());
  711. assert_eq!(_1_2.signum(), One::one());
  712. assert_eq!(_NEG1_2.signum(), - ::one::<Ratio<isize>>());
  713. assert!(_NEG1_2.is_negative());
  714. assert!(! _NEG1_2.is_positive());
  715. assert!(! _1_2.is_negative());
  716. }
  717. #[test]
  718. fn test_hash() {
  719. assert!(::hash(&_0) != ::hash(&_1));
  720. assert!(::hash(&_0) != ::hash(&_3_2));
  721. }
  722. }