rational.rs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983
  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. // Mathematically, comparing a/b and c/d is the same as comparing a*d and b*c, but it's very easy
  197. // for those multiplications to overflow fixed-size integers, so we need to take care.
  198. impl<T: Clone + Integer> Ord for Ratio<T> {
  199. #[inline]
  200. fn cmp(&self, other: &Self) -> cmp::Ordering {
  201. // With equal denominators, the numerators can be directly compared
  202. if self.denom == other.denom {
  203. let ord = self.numer.cmp(&other.numer);
  204. return if self.denom < T::zero() { ord.reverse() } else { ord };
  205. }
  206. // With equal numerators, the denominators can be inversely compared
  207. if self.numer == other.numer {
  208. let ord = self.denom.cmp(&other.denom);
  209. return if self.numer < T::zero() { ord } else { ord.reverse() };
  210. }
  211. // Unfortunately, we don't have CheckedMul to try. That could sometimes avoid all the
  212. // division below, or even always avoid it for BigInt and BigUint.
  213. // FIXME- future breaking change to add Checked* to Integer?
  214. // Compare as floored integers and remainders
  215. let (self_int, self_rem) = self.numer.div_mod_floor(&self.denom);
  216. let (other_int, other_rem) = other.numer.div_mod_floor(&other.denom);
  217. match self_int.cmp(&other_int) {
  218. cmp::Ordering::Greater => cmp::Ordering::Greater,
  219. cmp::Ordering::Less => cmp::Ordering::Less,
  220. cmp::Ordering::Equal => {
  221. match (self_rem.is_zero(), other_rem.is_zero()) {
  222. (true, true) => cmp::Ordering::Equal,
  223. (true, false) => cmp::Ordering::Less,
  224. (false, true) => cmp::Ordering::Greater,
  225. (false, false) => {
  226. // Compare the reciprocals of the remaining fractions in reverse
  227. let self_recip = Ratio::new_raw(self.denom.clone(), self_rem);
  228. let other_recip = Ratio::new_raw(other.denom.clone(), other_rem);
  229. self_recip.cmp(&other_recip).reverse()
  230. }
  231. }
  232. },
  233. }
  234. }
  235. }
  236. impl<T: Clone + Integer> PartialOrd for Ratio<T> {
  237. #[inline]
  238. fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
  239. Some(self.cmp(other))
  240. }
  241. }
  242. impl<T: Clone + Integer> PartialEq for Ratio<T> {
  243. #[inline]
  244. fn eq(&self, other: &Self) -> bool {
  245. self.cmp(other) == cmp::Ordering::Equal
  246. }
  247. }
  248. impl<T: Clone + Integer> Eq for Ratio<T> {}
  249. macro_rules! forward_val_val_binop {
  250. (impl $imp:ident, $method:ident) => {
  251. impl<T: Clone + Integer> $imp<Ratio<T>> for Ratio<T> {
  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_ref_val_binop {
  261. (impl $imp:ident, $method:ident) => {
  262. impl<'a, T> $imp<Ratio<T>> for &'a Ratio<T> where
  263. T: Clone + Integer
  264. {
  265. type Output = Ratio<T>;
  266. #[inline]
  267. fn $method(self, other: Ratio<T>) -> Ratio<T> {
  268. self.$method(&other)
  269. }
  270. }
  271. }
  272. }
  273. macro_rules! forward_val_ref_binop {
  274. (impl $imp:ident, $method:ident) => {
  275. impl<'a, T> $imp<&'a Ratio<T>> for Ratio<T> where
  276. T: Clone + Integer
  277. {
  278. type Output = Ratio<T>;
  279. #[inline]
  280. fn $method(self, other: &Ratio<T>) -> Ratio<T> {
  281. (&self).$method(other)
  282. }
  283. }
  284. }
  285. }
  286. macro_rules! forward_all_binop {
  287. (impl $imp:ident, $method:ident) => {
  288. forward_val_val_binop!(impl $imp, $method);
  289. forward_ref_val_binop!(impl $imp, $method);
  290. forward_val_ref_binop!(impl $imp, $method);
  291. };
  292. }
  293. /* Arithmetic */
  294. forward_all_binop!(impl Mul, mul);
  295. // a/b * c/d = (a*c)/(b*d)
  296. impl<'a, 'b, T> Mul<&'b Ratio<T>> for &'a Ratio<T>
  297. where T: Clone + Integer
  298. {
  299. type Output = Ratio<T>;
  300. #[inline]
  301. fn mul(self, rhs: &Ratio<T>) -> Ratio<T> {
  302. Ratio::new(self.numer.clone() * rhs.numer.clone(), self.denom.clone() * rhs.denom.clone())
  303. }
  304. }
  305. forward_all_binop!(impl Div, div);
  306. // (a/b) / (c/d) = (a*d)/(b*c)
  307. impl<'a, 'b, T> Div<&'b Ratio<T>> for &'a Ratio<T>
  308. where T: Clone + Integer
  309. {
  310. type Output = Ratio<T>;
  311. #[inline]
  312. fn div(self, rhs: &Ratio<T>) -> Ratio<T> {
  313. Ratio::new(self.numer.clone() * rhs.denom.clone(), self.denom.clone() * rhs.numer.clone())
  314. }
  315. }
  316. // Abstracts the a/b `op` c/d = (a*d `op` b*d) / (b*d) pattern
  317. macro_rules! arith_impl {
  318. (impl $imp:ident, $method:ident) => {
  319. forward_all_binop!(impl $imp, $method);
  320. impl<'a, 'b, T: Clone + Integer>
  321. $imp<&'b Ratio<T>> for &'a Ratio<T> {
  322. type Output = Ratio<T>;
  323. #[inline]
  324. fn $method(self, rhs: &Ratio<T>) -> Ratio<T> {
  325. Ratio::new((self.numer.clone() * rhs.denom.clone()).$method(self.denom.clone() * rhs.numer.clone()),
  326. self.denom.clone() * rhs.denom.clone())
  327. }
  328. }
  329. }
  330. }
  331. // a/b + c/d = (a*d + b*c)/(b*d)
  332. arith_impl!(impl Add, add);
  333. // a/b - c/d = (a*d - b*c)/(b*d)
  334. arith_impl!(impl Sub, sub);
  335. // a/b % c/d = (a*d % b*c)/(b*d)
  336. arith_impl!(impl Rem, rem);
  337. impl<T> Neg for Ratio<T>
  338. where T: Clone + Integer + Neg<Output = T>
  339. {
  340. type Output = Ratio<T>;
  341. #[inline]
  342. fn neg(self) -> Ratio<T> {
  343. Ratio::new_raw(-self.numer, self.denom)
  344. }
  345. }
  346. impl<'a, T> Neg for &'a Ratio<T>
  347. where T: Clone + Integer + Neg<Output = T>
  348. {
  349. type Output = Ratio<T>;
  350. #[inline]
  351. fn neg(self) -> Ratio<T> {
  352. -self.clone()
  353. }
  354. }
  355. /* Constants */
  356. impl<T: Clone + Integer>
  357. Zero for Ratio<T> {
  358. #[inline]
  359. fn zero() -> Ratio<T> {
  360. Ratio::new_raw(Zero::zero(), One::one())
  361. }
  362. #[inline]
  363. fn is_zero(&self) -> bool {
  364. self.numer.is_zero()
  365. }
  366. }
  367. impl<T: Clone + Integer>
  368. One for Ratio<T> {
  369. #[inline]
  370. fn one() -> Ratio<T> {
  371. Ratio::new_raw(One::one(), One::one())
  372. }
  373. }
  374. impl<T: Clone + Integer> Num for Ratio<T> {
  375. type FromStrRadixErr = ParseRatioError;
  376. /// Parses `numer/denom` where the numbers are in base `radix`.
  377. fn from_str_radix(s: &str, radix: u32) -> Result<Ratio<T>, ParseRatioError> {
  378. let split: Vec<&str> = s.splitn(2, '/').collect();
  379. if split.len() < 2 {
  380. Err(ParseRatioError{kind: RatioErrorKind::ParseError})
  381. } else {
  382. let a_result: Result<T, _> = T::from_str_radix(
  383. split[0],
  384. radix).map_err(|_| ParseRatioError{kind: RatioErrorKind::ParseError});
  385. a_result.and_then(|a| {
  386. let b_result: Result<T, _> =
  387. T::from_str_radix(split[1], radix).map_err(
  388. |_| ParseRatioError{kind: RatioErrorKind::ParseError});
  389. b_result.and_then(|b| if b.is_zero() {
  390. Err(ParseRatioError{kind: RatioErrorKind::ZeroDenominator})
  391. } else {
  392. Ok(Ratio::new(a.clone(), b.clone()))
  393. })
  394. })
  395. }
  396. }
  397. }
  398. impl<T: Clone + Integer + Signed> Signed for Ratio<T> {
  399. #[inline]
  400. fn abs(&self) -> Ratio<T> {
  401. if self.is_negative() { -self.clone() } else { self.clone() }
  402. }
  403. #[inline]
  404. fn abs_sub(&self, other: &Ratio<T>) -> Ratio<T> {
  405. if *self <= *other { Zero::zero() } else { self - other }
  406. }
  407. #[inline]
  408. fn signum(&self) -> Ratio<T> {
  409. if self.is_positive() {
  410. Self::one()
  411. } else if self.is_zero() {
  412. Self::zero()
  413. } else {
  414. - Self::one()
  415. }
  416. }
  417. #[inline]
  418. fn is_positive(&self) -> bool { !self.is_negative() }
  419. #[inline]
  420. fn is_negative(&self) -> bool {
  421. self.numer.is_negative() ^ self.denom.is_negative()
  422. }
  423. }
  424. /* String conversions */
  425. impl<T> fmt::Display for Ratio<T> where
  426. T: fmt::Display + Eq + One
  427. {
  428. /// Renders as `numer/denom`. If denom=1, renders as numer.
  429. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  430. if self.denom == One::one() {
  431. write!(f, "{}", self.numer)
  432. } else {
  433. write!(f, "{}/{}", self.numer, self.denom)
  434. }
  435. }
  436. }
  437. impl<T: FromStr + Clone + Integer> FromStr for Ratio<T> {
  438. type Err = ParseRatioError;
  439. /// Parses `numer/denom` or just `numer`.
  440. fn from_str(s: &str) -> Result<Ratio<T>, ParseRatioError> {
  441. let mut split = s.splitn(2, '/');
  442. let n = try!(split.next().ok_or(
  443. ParseRatioError{kind: RatioErrorKind::ParseError}));
  444. let num = try!(FromStr::from_str(n).map_err(
  445. |_| ParseRatioError{kind: RatioErrorKind::ParseError}));
  446. let d = split.next().unwrap_or("1");
  447. let den = try!(FromStr::from_str(d).map_err(
  448. |_| ParseRatioError{kind: RatioErrorKind::ParseError}));
  449. if Zero::is_zero(&den) {
  450. Err(ParseRatioError{kind: RatioErrorKind::ZeroDenominator})
  451. } else {
  452. Ok(Ratio::new(num, den))
  453. }
  454. }
  455. }
  456. // FIXME: Bubble up specific errors
  457. #[derive(Copy, Clone, Debug, PartialEq)]
  458. pub struct ParseRatioError { kind: RatioErrorKind }
  459. #[derive(Copy, Clone, Debug, PartialEq)]
  460. enum RatioErrorKind {
  461. ParseError,
  462. ZeroDenominator,
  463. }
  464. impl fmt::Display for ParseRatioError {
  465. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  466. self.description().fmt(f)
  467. }
  468. }
  469. impl Error for ParseRatioError {
  470. fn description(&self) -> &str { self.kind.description() }
  471. }
  472. impl RatioErrorKind {
  473. fn description(&self) -> &'static str {
  474. match *self {
  475. RatioErrorKind::ParseError => "failed to parse integer",
  476. RatioErrorKind::ZeroDenominator => "zero value denominator",
  477. }
  478. }
  479. }
  480. #[cfg(test)]
  481. mod test {
  482. use super::{Ratio, Rational};
  483. #[cfg(feature = "bigint")]
  484. use super::BigRational;
  485. use std::str::FromStr;
  486. use std::i32;
  487. use {Zero, One, Signed, FromPrimitive, Float};
  488. pub const _0 : Rational = Ratio { numer: 0, denom: 1};
  489. pub const _1 : Rational = Ratio { numer: 1, denom: 1};
  490. pub const _2: Rational = Ratio { numer: 2, denom: 1};
  491. pub const _1_2: Rational = Ratio { numer: 1, denom: 2};
  492. pub const _3_2: Rational = Ratio { numer: 3, denom: 2};
  493. pub const _NEG1_2: Rational = Ratio { numer: -1, denom: 2};
  494. pub const _1_3: Rational = Ratio { numer: 1, denom: 3};
  495. pub const _NEG1_3: Rational = Ratio { numer: -1, denom: 3};
  496. pub const _2_3: Rational = Ratio { numer: 2, denom: 3};
  497. pub const _NEG2_3: Rational = Ratio { numer: -2, denom: 3};
  498. #[cfg(feature = "bigint")]
  499. pub fn to_big(n: Rational) -> BigRational {
  500. Ratio::new(
  501. FromPrimitive::from_isize(n.numer).unwrap(),
  502. FromPrimitive::from_isize(n.denom).unwrap()
  503. )
  504. }
  505. #[cfg(not(feature = "bigint"))]
  506. pub fn to_big(n: Rational) -> Rational {
  507. Ratio::new(
  508. FromPrimitive::from_isize(n.numer).unwrap(),
  509. FromPrimitive::from_isize(n.denom).unwrap()
  510. )
  511. }
  512. #[test]
  513. fn test_test_constants() {
  514. // check our constants are what Ratio::new etc. would make.
  515. assert_eq!(_0, Zero::zero());
  516. assert_eq!(_1, One::one());
  517. assert_eq!(_2, Ratio::from_integer(2));
  518. assert_eq!(_1_2, Ratio::new(1,2));
  519. assert_eq!(_3_2, Ratio::new(3,2));
  520. assert_eq!(_NEG1_2, Ratio::new(-1,2));
  521. }
  522. #[test]
  523. fn test_new_reduce() {
  524. let one22 = Ratio::new(2,2);
  525. assert_eq!(one22, One::one());
  526. }
  527. #[test]
  528. #[should_panic]
  529. fn test_new_zero() {
  530. let _a = Ratio::new(1,0);
  531. }
  532. #[test]
  533. fn test_cmp() {
  534. assert!(_0 == _0 && _1 == _1);
  535. assert!(_0 != _1 && _1 != _0);
  536. assert!(_0 < _1 && !(_1 < _0));
  537. assert!(_1 > _0 && !(_0 > _1));
  538. assert!(_0 <= _0 && _1 <= _1);
  539. assert!(_0 <= _1 && !(_1 <= _0));
  540. assert!(_0 >= _0 && _1 >= _1);
  541. assert!(_1 >= _0 && !(_0 >= _1));
  542. }
  543. #[test]
  544. fn test_cmp_overflow() {
  545. use std::cmp::Ordering;
  546. // issue #7 example:
  547. let big = Ratio::new(128u8, 1);
  548. let small = big.recip();
  549. assert!(big > small);
  550. // try a few that are closer together
  551. // (some matching numer, some matching denom, some neither)
  552. let ratios = vec![
  553. Ratio::new(125_i8, 127_i8),
  554. Ratio::new(63_i8, 64_i8),
  555. Ratio::new(124_i8, 125_i8),
  556. Ratio::new(125_i8, 126_i8),
  557. Ratio::new(126_i8, 127_i8),
  558. Ratio::new(127_i8, 126_i8),
  559. ];
  560. fn check_cmp(a: Ratio<i8>, b: Ratio<i8>, ord: Ordering) {
  561. println!("comparing {} and {}", a, b);
  562. assert_eq!(a.cmp(&b), ord);
  563. assert_eq!(b.cmp(&a), ord.reverse());
  564. }
  565. for (i, &a) in ratios.iter().enumerate() {
  566. check_cmp(a, a, Ordering::Equal);
  567. check_cmp(-a, a, Ordering::Less);
  568. for &b in &ratios[i+1..] {
  569. check_cmp(a, b, Ordering::Less);
  570. check_cmp(-a, -b, Ordering::Greater);
  571. check_cmp(a.recip(), b.recip(), Ordering::Greater);
  572. check_cmp(-a.recip(), -b.recip(), Ordering::Less);
  573. }
  574. }
  575. }
  576. #[test]
  577. fn test_to_integer() {
  578. assert_eq!(_0.to_integer(), 0);
  579. assert_eq!(_1.to_integer(), 1);
  580. assert_eq!(_2.to_integer(), 2);
  581. assert_eq!(_1_2.to_integer(), 0);
  582. assert_eq!(_3_2.to_integer(), 1);
  583. assert_eq!(_NEG1_2.to_integer(), 0);
  584. }
  585. #[test]
  586. fn test_numer() {
  587. assert_eq!(_0.numer(), &0);
  588. assert_eq!(_1.numer(), &1);
  589. assert_eq!(_2.numer(), &2);
  590. assert_eq!(_1_2.numer(), &1);
  591. assert_eq!(_3_2.numer(), &3);
  592. assert_eq!(_NEG1_2.numer(), &(-1));
  593. }
  594. #[test]
  595. fn test_denom() {
  596. assert_eq!(_0.denom(), &1);
  597. assert_eq!(_1.denom(), &1);
  598. assert_eq!(_2.denom(), &1);
  599. assert_eq!(_1_2.denom(), &2);
  600. assert_eq!(_3_2.denom(), &2);
  601. assert_eq!(_NEG1_2.denom(), &2);
  602. }
  603. #[test]
  604. fn test_is_integer() {
  605. assert!(_0.is_integer());
  606. assert!(_1.is_integer());
  607. assert!(_2.is_integer());
  608. assert!(!_1_2.is_integer());
  609. assert!(!_3_2.is_integer());
  610. assert!(!_NEG1_2.is_integer());
  611. }
  612. #[test]
  613. fn test_show() {
  614. assert_eq!(format!("{}", _2), "2".to_string());
  615. assert_eq!(format!("{}", _1_2), "1/2".to_string());
  616. assert_eq!(format!("{}", _0), "0".to_string());
  617. assert_eq!(format!("{}", Ratio::from_integer(-2)), "-2".to_string());
  618. }
  619. mod arith {
  620. use super::{_0, _1, _2, _1_2, _3_2, _NEG1_2, to_big};
  621. use super::super::{Ratio, Rational};
  622. #[test]
  623. fn test_add() {
  624. fn test(a: Rational, b: Rational, c: Rational) {
  625. assert_eq!(a + b, c);
  626. assert_eq!(to_big(a) + to_big(b), to_big(c));
  627. }
  628. test(_1, _1_2, _3_2);
  629. test(_1, _1, _2);
  630. test(_1_2, _3_2, _2);
  631. test(_1_2, _NEG1_2, _0);
  632. }
  633. #[test]
  634. fn test_sub() {
  635. fn test(a: Rational, b: Rational, c: Rational) {
  636. assert_eq!(a - b, c);
  637. assert_eq!(to_big(a) - to_big(b), to_big(c))
  638. }
  639. test(_1, _1_2, _1_2);
  640. test(_3_2, _1_2, _1);
  641. test(_1, _NEG1_2, _3_2);
  642. }
  643. #[test]
  644. fn test_mul() {
  645. fn test(a: Rational, b: Rational, c: Rational) {
  646. assert_eq!(a * b, c);
  647. assert_eq!(to_big(a) * to_big(b), to_big(c))
  648. }
  649. test(_1, _1_2, _1_2);
  650. test(_1_2, _3_2, Ratio::new(3,4));
  651. test(_1_2, _NEG1_2, Ratio::new(-1, 4));
  652. }
  653. #[test]
  654. fn test_div() {
  655. fn test(a: Rational, b: Rational, c: Rational) {
  656. assert_eq!(a / b, c);
  657. assert_eq!(to_big(a) / to_big(b), to_big(c))
  658. }
  659. test(_1, _1_2, _2);
  660. test(_3_2, _1_2, _1 + _2);
  661. test(_1, _NEG1_2, _NEG1_2 + _NEG1_2 + _NEG1_2 + _NEG1_2);
  662. }
  663. #[test]
  664. fn test_rem() {
  665. fn test(a: Rational, b: Rational, c: Rational) {
  666. assert_eq!(a % b, c);
  667. assert_eq!(to_big(a) % to_big(b), to_big(c))
  668. }
  669. test(_3_2, _1, _1_2);
  670. test(_2, _NEG1_2, _0);
  671. test(_1_2, _2, _1_2);
  672. }
  673. #[test]
  674. fn test_neg() {
  675. fn test(a: Rational, b: Rational) {
  676. assert_eq!(-a, b);
  677. assert_eq!(-to_big(a), to_big(b))
  678. }
  679. test(_0, _0);
  680. test(_1_2, _NEG1_2);
  681. test(-_1, _1);
  682. }
  683. #[test]
  684. fn test_zero() {
  685. assert_eq!(_0 + _0, _0);
  686. assert_eq!(_0 * _0, _0);
  687. assert_eq!(_0 * _1, _0);
  688. assert_eq!(_0 / _NEG1_2, _0);
  689. assert_eq!(_0 - _0, _0);
  690. }
  691. #[test]
  692. #[should_panic]
  693. fn test_div_0() {
  694. let _a = _1 / _0;
  695. }
  696. }
  697. #[test]
  698. fn test_round() {
  699. assert_eq!(_1_3.ceil(), _1);
  700. assert_eq!(_1_3.floor(), _0);
  701. assert_eq!(_1_3.round(), _0);
  702. assert_eq!(_1_3.trunc(), _0);
  703. assert_eq!(_NEG1_3.ceil(), _0);
  704. assert_eq!(_NEG1_3.floor(), -_1);
  705. assert_eq!(_NEG1_3.round(), _0);
  706. assert_eq!(_NEG1_3.trunc(), _0);
  707. assert_eq!(_2_3.ceil(), _1);
  708. assert_eq!(_2_3.floor(), _0);
  709. assert_eq!(_2_3.round(), _1);
  710. assert_eq!(_2_3.trunc(), _0);
  711. assert_eq!(_NEG2_3.ceil(), _0);
  712. assert_eq!(_NEG2_3.floor(), -_1);
  713. assert_eq!(_NEG2_3.round(), -_1);
  714. assert_eq!(_NEG2_3.trunc(), _0);
  715. assert_eq!(_1_2.ceil(), _1);
  716. assert_eq!(_1_2.floor(), _0);
  717. assert_eq!(_1_2.round(), _1);
  718. assert_eq!(_1_2.trunc(), _0);
  719. assert_eq!(_NEG1_2.ceil(), _0);
  720. assert_eq!(_NEG1_2.floor(), -_1);
  721. assert_eq!(_NEG1_2.round(), -_1);
  722. assert_eq!(_NEG1_2.trunc(), _0);
  723. assert_eq!(_1.ceil(), _1);
  724. assert_eq!(_1.floor(), _1);
  725. assert_eq!(_1.round(), _1);
  726. assert_eq!(_1.trunc(), _1);
  727. // Overflow checks
  728. let _neg1 = Ratio::from_integer(-1);
  729. let _large_rat1 = Ratio::new(i32::MAX, i32::MAX-1);
  730. let _large_rat2 = Ratio::new(i32::MAX-1, i32::MAX);
  731. let _large_rat3 = Ratio::new(i32::MIN+2, i32::MIN+1);
  732. let _large_rat4 = Ratio::new(i32::MIN+1, i32::MIN+2);
  733. let _large_rat5 = Ratio::new(i32::MIN+2, i32::MAX);
  734. let _large_rat6 = Ratio::new(i32::MAX, i32::MIN+2);
  735. let _large_rat7 = Ratio::new(1, i32::MIN+1);
  736. let _large_rat8 = Ratio::new(1, i32::MAX);
  737. assert_eq!(_large_rat1.round(), One::one());
  738. assert_eq!(_large_rat2.round(), One::one());
  739. assert_eq!(_large_rat3.round(), One::one());
  740. assert_eq!(_large_rat4.round(), One::one());
  741. assert_eq!(_large_rat5.round(), _neg1);
  742. assert_eq!(_large_rat6.round(), _neg1);
  743. assert_eq!(_large_rat7.round(), Zero::zero());
  744. assert_eq!(_large_rat8.round(), Zero::zero());
  745. }
  746. #[test]
  747. fn test_fract() {
  748. assert_eq!(_1.fract(), _0);
  749. assert_eq!(_NEG1_2.fract(), _NEG1_2);
  750. assert_eq!(_1_2.fract(), _1_2);
  751. assert_eq!(_3_2.fract(), _1_2);
  752. }
  753. #[test]
  754. fn test_recip() {
  755. assert_eq!(_1 * _1.recip(), _1);
  756. assert_eq!(_2 * _2.recip(), _1);
  757. assert_eq!(_1_2 * _1_2.recip(), _1);
  758. assert_eq!(_3_2 * _3_2.recip(), _1);
  759. assert_eq!(_NEG1_2 * _NEG1_2.recip(), _1);
  760. }
  761. #[test]
  762. fn test_pow() {
  763. assert_eq!(_1_2.pow(2), Ratio::new(1, 4));
  764. assert_eq!(_1_2.pow(-2), Ratio::new(4, 1));
  765. assert_eq!(_1.pow(1), _1);
  766. assert_eq!(_NEG1_2.pow(2), _1_2.pow(2));
  767. assert_eq!(_NEG1_2.pow(3), -_1_2.pow(3));
  768. assert_eq!(_3_2.pow(0), _1);
  769. assert_eq!(_3_2.pow(-1), _3_2.recip());
  770. assert_eq!(_3_2.pow(3), Ratio::new(27, 8));
  771. }
  772. #[test]
  773. fn test_to_from_str() {
  774. fn test(r: Rational, s: String) {
  775. assert_eq!(FromStr::from_str(&s), Ok(r));
  776. assert_eq!(r.to_string(), s);
  777. }
  778. test(_1, "1".to_string());
  779. test(_0, "0".to_string());
  780. test(_1_2, "1/2".to_string());
  781. test(_3_2, "3/2".to_string());
  782. test(_2, "2".to_string());
  783. test(_NEG1_2, "-1/2".to_string());
  784. }
  785. #[test]
  786. fn test_from_str_fail() {
  787. fn test(s: &str) {
  788. let rational: Result<Rational, _> = FromStr::from_str(s);
  789. assert!(rational.is_err());
  790. }
  791. let xs = ["0 /1", "abc", "", "1/", "--1/2","3/2/1", "1/0"];
  792. for &s in xs.iter() {
  793. test(s);
  794. }
  795. }
  796. #[cfg(feature = "bigint")]
  797. #[test]
  798. fn test_from_float() {
  799. fn test<T: Float>(given: T, (numer, denom): (&str, &str)) {
  800. let ratio: BigRational = Ratio::from_float(given).unwrap();
  801. assert_eq!(ratio, Ratio::new(
  802. FromStr::from_str(numer).unwrap(),
  803. FromStr::from_str(denom).unwrap()));
  804. }
  805. // f32
  806. test(3.14159265359f32, ("13176795", "4194304"));
  807. test(2f32.powf(100.), ("1267650600228229401496703205376", "1"));
  808. test(-2f32.powf(100.), ("-1267650600228229401496703205376", "1"));
  809. test(1.0 / 2f32.powf(100.), ("1", "1267650600228229401496703205376"));
  810. test(684729.48391f32, ("1369459", "2"));
  811. test(-8573.5918555f32, ("-4389679", "512"));
  812. // f64
  813. test(3.14159265359f64, ("3537118876014453", "1125899906842624"));
  814. test(2f64.powf(100.), ("1267650600228229401496703205376", "1"));
  815. test(-2f64.powf(100.), ("-1267650600228229401496703205376", "1"));
  816. test(684729.48391f64, ("367611342500051", "536870912"));
  817. test(-8573.5918555f64, ("-4713381968463931", "549755813888"));
  818. test(1.0 / 2f64.powf(100.), ("1", "1267650600228229401496703205376"));
  819. }
  820. #[cfg(feature = "bigint")]
  821. #[test]
  822. fn test_from_float_fail() {
  823. use std::{f32, f64};
  824. assert_eq!(Ratio::from_float(f32::NAN), None);
  825. assert_eq!(Ratio::from_float(f32::INFINITY), None);
  826. assert_eq!(Ratio::from_float(f32::NEG_INFINITY), None);
  827. assert_eq!(Ratio::from_float(f64::NAN), None);
  828. assert_eq!(Ratio::from_float(f64::INFINITY), None);
  829. assert_eq!(Ratio::from_float(f64::NEG_INFINITY), None);
  830. }
  831. #[test]
  832. fn test_signed() {
  833. assert_eq!(_NEG1_2.abs(), _1_2);
  834. assert_eq!(_3_2.abs_sub(&_1_2), _1);
  835. assert_eq!(_1_2.abs_sub(&_3_2), Zero::zero());
  836. assert_eq!(_1_2.signum(), One::one());
  837. assert_eq!(_NEG1_2.signum(), - ::one::<Ratio<isize>>());
  838. assert!(_NEG1_2.is_negative());
  839. assert!(! _NEG1_2.is_positive());
  840. assert!(! _1_2.is_negative());
  841. }
  842. #[test]
  843. fn test_hash() {
  844. assert!(::hash(&_0) != ::hash(&_1));
  845. assert!(::hash(&_0) != ::hash(&_3_2));
  846. }
  847. }