rational.rs 27 KB

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