rational.rs 26 KB

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