rational.rs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912
  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> 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 + 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> $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
  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
  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
  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
  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>
  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 + Neg<Output = T>
  313. {
  314. type Output = Ratio<T>;
  315. #[inline]
  316. fn neg(self) -> Ratio<T> {
  317. Ratio::new_raw(-self.numer, self.denom)
  318. }
  319. }
  320. impl<'a, T> Neg for &'a Ratio<T>
  321. where T: Clone + Integer + Neg<Output = T>
  322. {
  323. type Output = Ratio<T>;
  324. #[inline]
  325. fn neg(self) -> Ratio<T> {
  326. -self.clone()
  327. }
  328. }
  329. /* Constants */
  330. impl<T: Clone + Integer>
  331. Zero for Ratio<T> {
  332. #[inline]
  333. fn zero() -> Ratio<T> {
  334. Ratio::new_raw(Zero::zero(), One::one())
  335. }
  336. #[inline]
  337. fn is_zero(&self) -> bool {
  338. self.numer.is_zero()
  339. }
  340. }
  341. impl<T: Clone + Integer>
  342. One for Ratio<T> {
  343. #[inline]
  344. fn one() -> Ratio<T> {
  345. Ratio::new_raw(One::one(), One::one())
  346. }
  347. }
  348. impl<T: Clone + Integer> Num for Ratio<T> {
  349. type FromStrRadixErr = ParseRatioError;
  350. /// Parses `numer/denom` where the numbers are in base `radix`.
  351. fn from_str_radix(s: &str, radix: u32) -> Result<Ratio<T>, ParseRatioError> {
  352. let split: Vec<&str> = s.splitn(2, '/').collect();
  353. if split.len() < 2 {
  354. Err(ParseRatioError{kind: RatioErrorKind::ParseError})
  355. } else {
  356. let a_result: Result<T, _> = T::from_str_radix(
  357. split[0],
  358. radix).map_err(|_| ParseRatioError{kind: RatioErrorKind::ParseError});
  359. a_result.and_then(|a| {
  360. let b_result: Result<T, _> =
  361. T::from_str_radix(split[1], radix).map_err(
  362. |_| ParseRatioError{kind: RatioErrorKind::ParseError});
  363. b_result.and_then(|b| if b.is_zero() {
  364. Err(ParseRatioError{kind: RatioErrorKind::ZeroDenominator})
  365. } else {
  366. Ok(Ratio::new(a.clone(), b.clone()))
  367. })
  368. })
  369. }
  370. }
  371. }
  372. impl<T: Clone + Integer + Signed> Signed for Ratio<T> {
  373. #[inline]
  374. fn abs(&self) -> Ratio<T> {
  375. if self.is_negative() { -self.clone() } else { self.clone() }
  376. }
  377. #[inline]
  378. fn abs_sub(&self, other: &Ratio<T>) -> Ratio<T> {
  379. if *self <= *other { Zero::zero() } else { self - other }
  380. }
  381. #[inline]
  382. fn signum(&self) -> Ratio<T> {
  383. if self.is_positive() {
  384. Self::one()
  385. } else if self.is_zero() {
  386. Self::zero()
  387. } else {
  388. - Self::one()
  389. }
  390. }
  391. #[inline]
  392. fn is_positive(&self) -> bool { !self.is_negative() }
  393. #[inline]
  394. fn is_negative(&self) -> bool {
  395. self.numer.is_negative() ^ self.denom.is_negative()
  396. }
  397. }
  398. /* String conversions */
  399. impl<T> fmt::Display for Ratio<T> where
  400. T: fmt::Display + Eq + One
  401. {
  402. /// Renders as `numer/denom`. If denom=1, renders as numer.
  403. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  404. if self.denom == One::one() {
  405. write!(f, "{}", self.numer)
  406. } else {
  407. write!(f, "{}/{}", self.numer, self.denom)
  408. }
  409. }
  410. }
  411. impl<T: FromStr + Clone + Integer> FromStr for Ratio<T> {
  412. type Err = ParseRatioError;
  413. /// Parses `numer/denom` or just `numer`.
  414. fn from_str(s: &str) -> Result<Ratio<T>, ParseRatioError> {
  415. let mut split = s.splitn(2, '/');
  416. let n = try!(split.next().ok_or(
  417. ParseRatioError{kind: RatioErrorKind::ParseError}));
  418. let num = try!(FromStr::from_str(n).map_err(
  419. |_| ParseRatioError{kind: RatioErrorKind::ParseError}));
  420. let d = split.next().unwrap_or("1");
  421. let den = try!(FromStr::from_str(d).map_err(
  422. |_| ParseRatioError{kind: RatioErrorKind::ParseError}));
  423. if Zero::is_zero(&den) {
  424. Err(ParseRatioError{kind: RatioErrorKind::ZeroDenominator})
  425. } else {
  426. Ok(Ratio::new(num, den))
  427. }
  428. }
  429. }
  430. // FIXME: Bubble up specific errors
  431. #[derive(Copy, Clone, Debug, PartialEq)]
  432. pub struct ParseRatioError { kind: RatioErrorKind }
  433. #[derive(Copy, Clone, Debug, PartialEq)]
  434. enum RatioErrorKind {
  435. ParseError,
  436. ZeroDenominator,
  437. }
  438. impl fmt::Display for ParseRatioError {
  439. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  440. self.description().fmt(f)
  441. }
  442. }
  443. impl Error for ParseRatioError {
  444. fn description(&self) -> &str { self.kind.description() }
  445. }
  446. impl RatioErrorKind {
  447. fn description(&self) -> &'static str {
  448. match *self {
  449. RatioErrorKind::ParseError => "failed to parse integer",
  450. RatioErrorKind::ZeroDenominator => "zero value denominator",
  451. }
  452. }
  453. }
  454. #[cfg(test)]
  455. mod test {
  456. use super::{Ratio, Rational};
  457. #[cfg(feature = "bigint")]
  458. use super::BigRational;
  459. use std::str::FromStr;
  460. use std::i32;
  461. use {Zero, One, Signed, FromPrimitive, Float};
  462. pub const _0 : Rational = Ratio { numer: 0, denom: 1};
  463. pub const _1 : Rational = Ratio { numer: 1, denom: 1};
  464. pub const _2: Rational = Ratio { numer: 2, denom: 1};
  465. pub const _1_2: Rational = Ratio { numer: 1, denom: 2};
  466. pub const _3_2: Rational = Ratio { numer: 3, denom: 2};
  467. pub const _NEG1_2: Rational = Ratio { numer: -1, denom: 2};
  468. pub const _1_3: Rational = Ratio { numer: 1, denom: 3};
  469. pub const _NEG1_3: Rational = Ratio { numer: -1, denom: 3};
  470. pub const _2_3: Rational = Ratio { numer: 2, denom: 3};
  471. pub const _NEG2_3: Rational = Ratio { numer: -2, denom: 3};
  472. #[cfg(feature = "bigint")]
  473. pub fn to_big(n: Rational) -> BigRational {
  474. Ratio::new(
  475. FromPrimitive::from_isize(n.numer).unwrap(),
  476. FromPrimitive::from_isize(n.denom).unwrap()
  477. )
  478. }
  479. #[cfg(not(feature = "bigint"))]
  480. pub fn to_big(n: Rational) -> Rational {
  481. Ratio::new(
  482. FromPrimitive::from_isize(n.numer).unwrap(),
  483. FromPrimitive::from_isize(n.denom).unwrap()
  484. )
  485. }
  486. #[test]
  487. fn test_test_constants() {
  488. // check our constants are what Ratio::new etc. would make.
  489. assert_eq!(_0, Zero::zero());
  490. assert_eq!(_1, One::one());
  491. assert_eq!(_2, Ratio::from_integer(2));
  492. assert_eq!(_1_2, Ratio::new(1,2));
  493. assert_eq!(_3_2, Ratio::new(3,2));
  494. assert_eq!(_NEG1_2, Ratio::new(-1,2));
  495. }
  496. #[test]
  497. fn test_new_reduce() {
  498. let one22 = Ratio::new(2,2);
  499. assert_eq!(one22, One::one());
  500. }
  501. #[test]
  502. #[should_panic]
  503. fn test_new_zero() {
  504. let _a = Ratio::new(1,0);
  505. }
  506. #[test]
  507. fn test_cmp() {
  508. assert!(_0 == _0 && _1 == _1);
  509. assert!(_0 != _1 && _1 != _0);
  510. assert!(_0 < _1 && !(_1 < _0));
  511. assert!(_1 > _0 && !(_0 > _1));
  512. assert!(_0 <= _0 && _1 <= _1);
  513. assert!(_0 <= _1 && !(_1 <= _0));
  514. assert!(_0 >= _0 && _1 >= _1);
  515. assert!(_1 >= _0 && !(_0 >= _1));
  516. }
  517. #[test]
  518. fn test_to_integer() {
  519. assert_eq!(_0.to_integer(), 0);
  520. assert_eq!(_1.to_integer(), 1);
  521. assert_eq!(_2.to_integer(), 2);
  522. assert_eq!(_1_2.to_integer(), 0);
  523. assert_eq!(_3_2.to_integer(), 1);
  524. assert_eq!(_NEG1_2.to_integer(), 0);
  525. }
  526. #[test]
  527. fn test_numer() {
  528. assert_eq!(_0.numer(), &0);
  529. assert_eq!(_1.numer(), &1);
  530. assert_eq!(_2.numer(), &2);
  531. assert_eq!(_1_2.numer(), &1);
  532. assert_eq!(_3_2.numer(), &3);
  533. assert_eq!(_NEG1_2.numer(), &(-1));
  534. }
  535. #[test]
  536. fn test_denom() {
  537. assert_eq!(_0.denom(), &1);
  538. assert_eq!(_1.denom(), &1);
  539. assert_eq!(_2.denom(), &1);
  540. assert_eq!(_1_2.denom(), &2);
  541. assert_eq!(_3_2.denom(), &2);
  542. assert_eq!(_NEG1_2.denom(), &2);
  543. }
  544. #[test]
  545. fn test_is_integer() {
  546. assert!(_0.is_integer());
  547. assert!(_1.is_integer());
  548. assert!(_2.is_integer());
  549. assert!(!_1_2.is_integer());
  550. assert!(!_3_2.is_integer());
  551. assert!(!_NEG1_2.is_integer());
  552. }
  553. #[test]
  554. fn test_show() {
  555. assert_eq!(format!("{}", _2), "2".to_string());
  556. assert_eq!(format!("{}", _1_2), "1/2".to_string());
  557. assert_eq!(format!("{}", _0), "0".to_string());
  558. assert_eq!(format!("{}", Ratio::from_integer(-2)), "-2".to_string());
  559. }
  560. mod arith {
  561. use super::{_0, _1, _2, _1_2, _3_2, _NEG1_2, to_big};
  562. use super::super::{Ratio, Rational};
  563. #[test]
  564. fn test_add() {
  565. fn test(a: Rational, b: Rational, c: Rational) {
  566. assert_eq!(a + b, c);
  567. assert_eq!(to_big(a) + to_big(b), to_big(c));
  568. }
  569. test(_1, _1_2, _3_2);
  570. test(_1, _1, _2);
  571. test(_1_2, _3_2, _2);
  572. test(_1_2, _NEG1_2, _0);
  573. }
  574. #[test]
  575. fn test_sub() {
  576. fn test(a: Rational, b: Rational, c: Rational) {
  577. assert_eq!(a - b, c);
  578. assert_eq!(to_big(a) - to_big(b), to_big(c))
  579. }
  580. test(_1, _1_2, _1_2);
  581. test(_3_2, _1_2, _1);
  582. test(_1, _NEG1_2, _3_2);
  583. }
  584. #[test]
  585. fn test_mul() {
  586. fn test(a: Rational, b: Rational, c: Rational) {
  587. assert_eq!(a * b, c);
  588. assert_eq!(to_big(a) * to_big(b), to_big(c))
  589. }
  590. test(_1, _1_2, _1_2);
  591. test(_1_2, _3_2, Ratio::new(3,4));
  592. test(_1_2, _NEG1_2, Ratio::new(-1, 4));
  593. }
  594. #[test]
  595. fn test_div() {
  596. fn test(a: Rational, b: Rational, c: Rational) {
  597. assert_eq!(a / b, c);
  598. assert_eq!(to_big(a) / to_big(b), to_big(c))
  599. }
  600. test(_1, _1_2, _2);
  601. test(_3_2, _1_2, _1 + _2);
  602. test(_1, _NEG1_2, _NEG1_2 + _NEG1_2 + _NEG1_2 + _NEG1_2);
  603. }
  604. #[test]
  605. fn test_rem() {
  606. fn test(a: Rational, b: Rational, c: Rational) {
  607. assert_eq!(a % b, c);
  608. assert_eq!(to_big(a) % to_big(b), to_big(c))
  609. }
  610. test(_3_2, _1, _1_2);
  611. test(_2, _NEG1_2, _0);
  612. test(_1_2, _2, _1_2);
  613. }
  614. #[test]
  615. fn test_neg() {
  616. fn test(a: Rational, b: Rational) {
  617. assert_eq!(-a, b);
  618. assert_eq!(-to_big(a), to_big(b))
  619. }
  620. test(_0, _0);
  621. test(_1_2, _NEG1_2);
  622. test(-_1, _1);
  623. }
  624. #[test]
  625. fn test_zero() {
  626. assert_eq!(_0 + _0, _0);
  627. assert_eq!(_0 * _0, _0);
  628. assert_eq!(_0 * _1, _0);
  629. assert_eq!(_0 / _NEG1_2, _0);
  630. assert_eq!(_0 - _0, _0);
  631. }
  632. #[test]
  633. #[should_panic]
  634. fn test_div_0() {
  635. let _a = _1 / _0;
  636. }
  637. }
  638. #[test]
  639. fn test_round() {
  640. assert_eq!(_1_3.ceil(), _1);
  641. assert_eq!(_1_3.floor(), _0);
  642. assert_eq!(_1_3.round(), _0);
  643. assert_eq!(_1_3.trunc(), _0);
  644. assert_eq!(_NEG1_3.ceil(), _0);
  645. assert_eq!(_NEG1_3.floor(), -_1);
  646. assert_eq!(_NEG1_3.round(), _0);
  647. assert_eq!(_NEG1_3.trunc(), _0);
  648. assert_eq!(_2_3.ceil(), _1);
  649. assert_eq!(_2_3.floor(), _0);
  650. assert_eq!(_2_3.round(), _1);
  651. assert_eq!(_2_3.trunc(), _0);
  652. assert_eq!(_NEG2_3.ceil(), _0);
  653. assert_eq!(_NEG2_3.floor(), -_1);
  654. assert_eq!(_NEG2_3.round(), -_1);
  655. assert_eq!(_NEG2_3.trunc(), _0);
  656. assert_eq!(_1_2.ceil(), _1);
  657. assert_eq!(_1_2.floor(), _0);
  658. assert_eq!(_1_2.round(), _1);
  659. assert_eq!(_1_2.trunc(), _0);
  660. assert_eq!(_NEG1_2.ceil(), _0);
  661. assert_eq!(_NEG1_2.floor(), -_1);
  662. assert_eq!(_NEG1_2.round(), -_1);
  663. assert_eq!(_NEG1_2.trunc(), _0);
  664. assert_eq!(_1.ceil(), _1);
  665. assert_eq!(_1.floor(), _1);
  666. assert_eq!(_1.round(), _1);
  667. assert_eq!(_1.trunc(), _1);
  668. // Overflow checks
  669. let _neg1 = Ratio::from_integer(-1);
  670. let _large_rat1 = Ratio::new(i32::MAX, i32::MAX-1);
  671. let _large_rat2 = Ratio::new(i32::MAX-1, i32::MAX);
  672. let _large_rat3 = Ratio::new(i32::MIN+2, i32::MIN+1);
  673. let _large_rat4 = Ratio::new(i32::MIN+1, i32::MIN+2);
  674. let _large_rat5 = Ratio::new(i32::MIN+2, i32::MAX);
  675. let _large_rat6 = Ratio::new(i32::MAX, i32::MIN+2);
  676. let _large_rat7 = Ratio::new(1, i32::MIN+1);
  677. let _large_rat8 = Ratio::new(1, i32::MAX);
  678. assert_eq!(_large_rat1.round(), One::one());
  679. assert_eq!(_large_rat2.round(), One::one());
  680. assert_eq!(_large_rat3.round(), One::one());
  681. assert_eq!(_large_rat4.round(), One::one());
  682. assert_eq!(_large_rat5.round(), _neg1);
  683. assert_eq!(_large_rat6.round(), _neg1);
  684. assert_eq!(_large_rat7.round(), Zero::zero());
  685. assert_eq!(_large_rat8.round(), Zero::zero());
  686. }
  687. #[test]
  688. fn test_fract() {
  689. assert_eq!(_1.fract(), _0);
  690. assert_eq!(_NEG1_2.fract(), _NEG1_2);
  691. assert_eq!(_1_2.fract(), _1_2);
  692. assert_eq!(_3_2.fract(), _1_2);
  693. }
  694. #[test]
  695. fn test_recip() {
  696. assert_eq!(_1 * _1.recip(), _1);
  697. assert_eq!(_2 * _2.recip(), _1);
  698. assert_eq!(_1_2 * _1_2.recip(), _1);
  699. assert_eq!(_3_2 * _3_2.recip(), _1);
  700. assert_eq!(_NEG1_2 * _NEG1_2.recip(), _1);
  701. }
  702. #[test]
  703. fn test_pow() {
  704. assert_eq!(_1_2.pow(2), Ratio::new(1, 4));
  705. assert_eq!(_1_2.pow(-2), Ratio::new(4, 1));
  706. assert_eq!(_1.pow(1), _1);
  707. assert_eq!(_NEG1_2.pow(2), _1_2.pow(2));
  708. assert_eq!(_NEG1_2.pow(3), -_1_2.pow(3));
  709. assert_eq!(_3_2.pow(0), _1);
  710. assert_eq!(_3_2.pow(-1), _3_2.recip());
  711. assert_eq!(_3_2.pow(3), Ratio::new(27, 8));
  712. }
  713. #[test]
  714. fn test_to_from_str() {
  715. fn test(r: Rational, s: String) {
  716. assert_eq!(FromStr::from_str(&s), Ok(r));
  717. assert_eq!(r.to_string(), s);
  718. }
  719. test(_1, "1".to_string());
  720. test(_0, "0".to_string());
  721. test(_1_2, "1/2".to_string());
  722. test(_3_2, "3/2".to_string());
  723. test(_2, "2".to_string());
  724. test(_NEG1_2, "-1/2".to_string());
  725. }
  726. #[test]
  727. fn test_from_str_fail() {
  728. fn test(s: &str) {
  729. let rational: Result<Rational, _> = FromStr::from_str(s);
  730. assert!(rational.is_err());
  731. }
  732. let xs = ["0 /1", "abc", "", "1/", "--1/2","3/2/1", "1/0"];
  733. for &s in xs.iter() {
  734. test(s);
  735. }
  736. }
  737. #[cfg(feature = "bigint")]
  738. #[test]
  739. fn test_from_float() {
  740. fn test<T: Float>(given: T, (numer, denom): (&str, &str)) {
  741. let ratio: BigRational = Ratio::from_float(given).unwrap();
  742. assert_eq!(ratio, Ratio::new(
  743. FromStr::from_str(numer).unwrap(),
  744. FromStr::from_str(denom).unwrap()));
  745. }
  746. // f32
  747. test(3.14159265359f32, ("13176795", "4194304"));
  748. test(2f32.powf(100.), ("1267650600228229401496703205376", "1"));
  749. test(-2f32.powf(100.), ("-1267650600228229401496703205376", "1"));
  750. test(1.0 / 2f32.powf(100.), ("1", "1267650600228229401496703205376"));
  751. test(684729.48391f32, ("1369459", "2"));
  752. test(-8573.5918555f32, ("-4389679", "512"));
  753. // f64
  754. test(3.14159265359f64, ("3537118876014453", "1125899906842624"));
  755. test(2f64.powf(100.), ("1267650600228229401496703205376", "1"));
  756. test(-2f64.powf(100.), ("-1267650600228229401496703205376", "1"));
  757. test(684729.48391f64, ("367611342500051", "536870912"));
  758. test(-8573.5918555f64, ("-4713381968463931", "549755813888"));
  759. test(1.0 / 2f64.powf(100.), ("1", "1267650600228229401496703205376"));
  760. }
  761. #[cfg(feature = "bigint")]
  762. #[test]
  763. fn test_from_float_fail() {
  764. use std::{f32, f64};
  765. assert_eq!(Ratio::from_float(f32::NAN), None);
  766. assert_eq!(Ratio::from_float(f32::INFINITY), None);
  767. assert_eq!(Ratio::from_float(f32::NEG_INFINITY), None);
  768. assert_eq!(Ratio::from_float(f64::NAN), None);
  769. assert_eq!(Ratio::from_float(f64::INFINITY), None);
  770. assert_eq!(Ratio::from_float(f64::NEG_INFINITY), None);
  771. }
  772. #[test]
  773. fn test_signed() {
  774. assert_eq!(_NEG1_2.abs(), _1_2);
  775. assert_eq!(_3_2.abs_sub(&_1_2), _1);
  776. assert_eq!(_1_2.abs_sub(&_3_2), Zero::zero());
  777. assert_eq!(_1_2.signum(), One::one());
  778. assert_eq!(_NEG1_2.signum(), - ::one::<Ratio<isize>>());
  779. assert!(_NEG1_2.is_negative());
  780. assert!(! _NEG1_2.is_positive());
  781. assert!(! _1_2.is_negative());
  782. }
  783. #[test]
  784. fn test_hash() {
  785. assert!(::hash(&_0) != ::hash(&_1));
  786. assert!(::hash(&_0) != ::hash(&_3_2));
  787. }
  788. }