rational.rs 25 KB

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