lib.rs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092
  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. #[cfg(feature = "serde")]
  12. extern crate serde;
  13. #[cfg(feature = "num-bigint")]
  14. extern crate num_bigint as bigint;
  15. extern crate num_traits as traits;
  16. extern crate num_integer as integer;
  17. use std::cmp;
  18. use std::error::Error;
  19. use std::fmt;
  20. #[cfg(test)]
  21. use std::hash;
  22. use std::ops::{Add, Div, Mul, Neg, Rem, Sub};
  23. use std::str::FromStr;
  24. #[cfg(feature = "serde")]
  25. use serde;
  26. #[cfg(feature = "num-bigint")]
  27. use bigint::{BigInt, BigUint, Sign};
  28. use integer::Integer;
  29. use traits::{FromPrimitive, Float, PrimInt, Num, Signed, Zero, One};
  30. /// Represents the ratio between 2 numbers.
  31. #[derive(Copy, Clone, Hash, Debug)]
  32. #[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))]
  33. #[allow(missing_docs)]
  34. pub struct Ratio<T> {
  35. numer: T,
  36. denom: T,
  37. }
  38. /// Alias for a `Ratio` of machine-sized integers.
  39. pub type Rational = Ratio<isize>;
  40. pub type Rational32 = Ratio<i32>;
  41. pub type Rational64 = Ratio<i64>;
  42. #[cfg(feature = "num-bigint")]
  43. /// Alias for arbitrary precision rationals.
  44. pub type BigRational = Ratio<BigInt>;
  45. impl<T: Clone + Integer> Ratio<T> {
  46. /// Creates a ratio representing the integer `t`.
  47. #[inline]
  48. pub fn from_integer(t: T) -> Ratio<T> {
  49. Ratio::new_raw(t, One::one())
  50. }
  51. /// Creates a ratio without checking for `denom == 0` or reducing.
  52. #[inline]
  53. pub fn new_raw(numer: T, denom: T) -> Ratio<T> {
  54. Ratio {
  55. numer: numer,
  56. denom: denom,
  57. }
  58. }
  59. /// Create a new Ratio. Fails if `denom == 0`.
  60. #[inline]
  61. pub fn new(numer: T, denom: T) -> Ratio<T> {
  62. if denom == Zero::zero() {
  63. panic!("denominator == 0");
  64. }
  65. let mut ret = Ratio::new_raw(numer, denom);
  66. ret.reduce();
  67. ret
  68. }
  69. /// Converts to an integer.
  70. #[inline]
  71. pub fn to_integer(&self) -> T {
  72. self.trunc().numer
  73. }
  74. /// Gets an immutable reference to the numerator.
  75. #[inline]
  76. pub fn numer<'a>(&'a self) -> &'a T {
  77. &self.numer
  78. }
  79. /// Gets an immutable reference to the denominator.
  80. #[inline]
  81. pub fn denom<'a>(&'a self) -> &'a T {
  82. &self.denom
  83. }
  84. /// Returns true if the rational number is an integer (denominator is 1).
  85. #[inline]
  86. pub fn is_integer(&self) -> bool {
  87. self.denom == One::one()
  88. }
  89. /// Put self into lowest terms, with denom > 0.
  90. fn reduce(&mut self) {
  91. let g: T = self.numer.gcd(&self.denom);
  92. // FIXME(#5992): assignment operator overloads
  93. // self.numer /= g;
  94. self.numer = self.numer.clone() / g.clone();
  95. // FIXME(#5992): assignment operator overloads
  96. // self.denom /= g;
  97. self.denom = self.denom.clone() / g;
  98. // keep denom positive!
  99. if self.denom < T::zero() {
  100. self.numer = T::zero() - self.numer.clone();
  101. self.denom = T::zero() - self.denom.clone();
  102. }
  103. }
  104. /// Returns a `reduce`d copy of self.
  105. pub fn reduced(&self) -> Ratio<T> {
  106. let mut ret = self.clone();
  107. ret.reduce();
  108. ret
  109. }
  110. /// Returns the reciprocal.
  111. #[inline]
  112. pub fn recip(&self) -> Ratio<T> {
  113. Ratio::new_raw(self.denom.clone(), self.numer.clone())
  114. }
  115. /// Rounds towards minus infinity.
  116. #[inline]
  117. pub fn floor(&self) -> Ratio<T> {
  118. if *self < Zero::zero() {
  119. let one: T = One::one();
  120. Ratio::from_integer((self.numer.clone() - self.denom.clone() + one) /
  121. self.denom.clone())
  122. } else {
  123. Ratio::from_integer(self.numer.clone() / self.denom.clone())
  124. }
  125. }
  126. /// Rounds towards plus infinity.
  127. #[inline]
  128. pub fn ceil(&self) -> Ratio<T> {
  129. if *self < Zero::zero() {
  130. Ratio::from_integer(self.numer.clone() / self.denom.clone())
  131. } else {
  132. let one: T = One::one();
  133. Ratio::from_integer((self.numer.clone() + self.denom.clone() - one) /
  134. self.denom.clone())
  135. }
  136. }
  137. /// Rounds to the nearest integer. Rounds half-way cases away from zero.
  138. #[inline]
  139. pub fn round(&self) -> Ratio<T> {
  140. let zero: Ratio<T> = Zero::zero();
  141. let one: T = One::one();
  142. let two: T = one.clone() + one.clone();
  143. // Find unsigned fractional part of rational number
  144. let mut fractional = self.fract();
  145. if fractional < zero {
  146. fractional = zero - fractional
  147. };
  148. // The algorithm compares the unsigned fractional part with 1/2, that
  149. // is, a/b >= 1/2, or a >= b/2. For odd denominators, we use
  150. // a >= (b/2)+1. This avoids overflow issues.
  151. let half_or_larger = if fractional.denom().is_even() {
  152. *fractional.numer() >= fractional.denom().clone() / two.clone()
  153. } else {
  154. *fractional.numer() >= (fractional.denom().clone() / two.clone()) + one.clone()
  155. };
  156. if half_or_larger {
  157. let one: Ratio<T> = One::one();
  158. if *self >= Zero::zero() {
  159. self.trunc() + one
  160. } else {
  161. self.trunc() - one
  162. }
  163. } else {
  164. self.trunc()
  165. }
  166. }
  167. /// Rounds towards zero.
  168. #[inline]
  169. pub fn trunc(&self) -> Ratio<T> {
  170. Ratio::from_integer(self.numer.clone() / self.denom.clone())
  171. }
  172. /// Returns the fractional part of a number.
  173. #[inline]
  174. pub fn fract(&self) -> Ratio<T> {
  175. Ratio::new_raw(self.numer.clone() % self.denom.clone(), self.denom.clone())
  176. }
  177. }
  178. impl<T: Clone + Integer + PrimInt> Ratio<T> {
  179. /// Raises the ratio to the power of an exponent
  180. #[inline]
  181. pub fn pow(&self, expon: i32) -> Ratio<T> {
  182. match expon.cmp(&0) {
  183. cmp::Ordering::Equal => One::one(),
  184. cmp::Ordering::Less => self.recip().pow(-expon),
  185. cmp::Ordering::Greater => {
  186. Ratio::new_raw(self.numer.pow(expon as u32), self.denom.pow(expon as u32))
  187. }
  188. }
  189. }
  190. }
  191. #[cfg(feature = "num-bigint")]
  192. impl Ratio<BigInt> {
  193. /// Converts a float into a rational number.
  194. pub fn from_float<T: Float>(f: T) -> Option<BigRational> {
  195. if !f.is_finite() {
  196. return None;
  197. }
  198. let (mantissa, exponent, sign) = f.integer_decode();
  199. let bigint_sign = if sign == 1 {
  200. Sign::Plus
  201. } else {
  202. Sign::Minus
  203. };
  204. if exponent < 0 {
  205. let one: BigInt = One::one();
  206. let denom: BigInt = one << ((-exponent) as usize);
  207. let numer: BigUint = FromPrimitive::from_u64(mantissa).unwrap();
  208. Some(Ratio::new(BigInt::from_biguint(bigint_sign, numer), denom))
  209. } else {
  210. let mut numer: BigUint = FromPrimitive::from_u64(mantissa).unwrap();
  211. numer = numer << (exponent as usize);
  212. Some(Ratio::from_integer(BigInt::from_biguint(bigint_sign, numer)))
  213. }
  214. }
  215. }
  216. // Comparisons
  217. // Mathematically, comparing a/b and c/d is the same as comparing a*d and b*c, but it's very easy
  218. // for those multiplications to overflow fixed-size integers, so we need to take care.
  219. impl<T: Clone + Integer> Ord for Ratio<T> {
  220. #[inline]
  221. fn cmp(&self, other: &Self) -> cmp::Ordering {
  222. // With equal denominators, the numerators can be directly compared
  223. if self.denom == other.denom {
  224. let ord = self.numer.cmp(&other.numer);
  225. return if self.denom < T::zero() {
  226. ord.reverse()
  227. } else {
  228. ord
  229. };
  230. }
  231. // With equal numerators, the denominators can be inversely compared
  232. if self.numer == other.numer {
  233. let ord = self.denom.cmp(&other.denom);
  234. return if self.numer < T::zero() {
  235. ord
  236. } else {
  237. ord.reverse()
  238. };
  239. }
  240. // Unfortunately, we don't have CheckedMul to try. That could sometimes avoid all the
  241. // division below, or even always avoid it for BigInt and BigUint.
  242. // FIXME- future breaking change to add Checked* to Integer?
  243. // Compare as floored integers and remainders
  244. let (self_int, self_rem) = self.numer.div_mod_floor(&self.denom);
  245. let (other_int, other_rem) = other.numer.div_mod_floor(&other.denom);
  246. match self_int.cmp(&other_int) {
  247. cmp::Ordering::Greater => cmp::Ordering::Greater,
  248. cmp::Ordering::Less => cmp::Ordering::Less,
  249. cmp::Ordering::Equal => {
  250. match (self_rem.is_zero(), other_rem.is_zero()) {
  251. (true, true) => cmp::Ordering::Equal,
  252. (true, false) => cmp::Ordering::Less,
  253. (false, true) => cmp::Ordering::Greater,
  254. (false, false) => {
  255. // Compare the reciprocals of the remaining fractions in reverse
  256. let self_recip = Ratio::new_raw(self.denom.clone(), self_rem);
  257. let other_recip = Ratio::new_raw(other.denom.clone(), other_rem);
  258. self_recip.cmp(&other_recip).reverse()
  259. }
  260. }
  261. }
  262. }
  263. }
  264. }
  265. impl<T: Clone + Integer> PartialOrd for Ratio<T> {
  266. #[inline]
  267. fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
  268. Some(self.cmp(other))
  269. }
  270. }
  271. impl<T: Clone + Integer> PartialEq for Ratio<T> {
  272. #[inline]
  273. fn eq(&self, other: &Self) -> bool {
  274. self.cmp(other) == cmp::Ordering::Equal
  275. }
  276. }
  277. impl<T: Clone + Integer> Eq for Ratio<T> {}
  278. macro_rules! forward_val_val_binop {
  279. (impl $imp:ident, $method:ident) => {
  280. impl<T: Clone + Integer> $imp<Ratio<T>> for Ratio<T> {
  281. type Output = Ratio<T>;
  282. #[inline]
  283. fn $method(self, other: Ratio<T>) -> Ratio<T> {
  284. (&self).$method(&other)
  285. }
  286. }
  287. }
  288. }
  289. macro_rules! forward_ref_val_binop {
  290. (impl $imp:ident, $method:ident) => {
  291. impl<'a, T> $imp<Ratio<T>> for &'a Ratio<T> where
  292. T: Clone + Integer
  293. {
  294. type Output = Ratio<T>;
  295. #[inline]
  296. fn $method(self, other: Ratio<T>) -> Ratio<T> {
  297. self.$method(&other)
  298. }
  299. }
  300. }
  301. }
  302. macro_rules! forward_val_ref_binop {
  303. (impl $imp:ident, $method:ident) => {
  304. impl<'a, T> $imp<&'a Ratio<T>> for Ratio<T> where
  305. T: Clone + Integer
  306. {
  307. type Output = Ratio<T>;
  308. #[inline]
  309. fn $method(self, other: &Ratio<T>) -> Ratio<T> {
  310. (&self).$method(other)
  311. }
  312. }
  313. }
  314. }
  315. macro_rules! forward_all_binop {
  316. (impl $imp:ident, $method:ident) => {
  317. forward_val_val_binop!(impl $imp, $method);
  318. forward_ref_val_binop!(impl $imp, $method);
  319. forward_val_ref_binop!(impl $imp, $method);
  320. };
  321. }
  322. // Arithmetic
  323. forward_all_binop!(impl Mul, mul);
  324. // a/b * c/d = (a*c)/(b*d)
  325. impl<'a, 'b, T> Mul<&'b Ratio<T>> for &'a Ratio<T>
  326. where T: Clone + Integer
  327. {
  328. type Output = Ratio<T>;
  329. #[inline]
  330. fn mul(self, rhs: &Ratio<T>) -> Ratio<T> {
  331. Ratio::new(self.numer.clone() * rhs.numer.clone(),
  332. self.denom.clone() * rhs.denom.clone())
  333. }
  334. }
  335. forward_all_binop!(impl Div, div);
  336. // (a/b) / (c/d) = (a*d)/(b*c)
  337. impl<'a, 'b, T> Div<&'b Ratio<T>> for &'a Ratio<T>
  338. where T: Clone + Integer
  339. {
  340. type Output = Ratio<T>;
  341. #[inline]
  342. fn div(self, rhs: &Ratio<T>) -> Ratio<T> {
  343. Ratio::new(self.numer.clone() * rhs.denom.clone(),
  344. self.denom.clone() * rhs.numer.clone())
  345. }
  346. }
  347. // Abstracts the a/b `op` c/d = (a*d `op` b*d) / (b*d) pattern
  348. macro_rules! arith_impl {
  349. (impl $imp:ident, $method:ident) => {
  350. forward_all_binop!(impl $imp, $method);
  351. impl<'a, 'b, T: Clone + Integer>
  352. $imp<&'b Ratio<T>> for &'a Ratio<T> {
  353. type Output = Ratio<T>;
  354. #[inline]
  355. fn $method(self, rhs: &Ratio<T>) -> Ratio<T> {
  356. Ratio::new((self.numer.clone() * rhs.denom.clone()).$method(self.denom.clone() * rhs.numer.clone()),
  357. self.denom.clone() * rhs.denom.clone())
  358. }
  359. }
  360. }
  361. }
  362. // a/b + c/d = (a*d + b*c)/(b*d)
  363. arith_impl!(impl Add, add);
  364. // a/b - c/d = (a*d - b*c)/(b*d)
  365. arith_impl!(impl Sub, sub);
  366. // a/b % c/d = (a*d % b*c)/(b*d)
  367. arith_impl!(impl Rem, rem);
  368. impl<T> Neg for Ratio<T>
  369. where T: Clone + Integer + Neg<Output = T>
  370. {
  371. type Output = Ratio<T>;
  372. #[inline]
  373. fn neg(self) -> Ratio<T> {
  374. Ratio::new_raw(-self.numer, self.denom)
  375. }
  376. }
  377. impl<'a, T> Neg for &'a Ratio<T>
  378. where T: Clone + Integer + Neg<Output = T>
  379. {
  380. type Output = Ratio<T>;
  381. #[inline]
  382. fn neg(self) -> Ratio<T> {
  383. -self.clone()
  384. }
  385. }
  386. // Constants
  387. impl<T: Clone + Integer> Zero for Ratio<T> {
  388. #[inline]
  389. fn zero() -> Ratio<T> {
  390. Ratio::new_raw(Zero::zero(), One::one())
  391. }
  392. #[inline]
  393. fn is_zero(&self) -> bool {
  394. self.numer.is_zero()
  395. }
  396. }
  397. impl<T: Clone + Integer> One for Ratio<T> {
  398. #[inline]
  399. fn one() -> Ratio<T> {
  400. Ratio::new_raw(One::one(), One::one())
  401. }
  402. }
  403. impl<T: Clone + Integer> Num for Ratio<T> {
  404. type FromStrRadixErr = ParseRatioError;
  405. /// Parses `numer/denom` where the numbers are in base `radix`.
  406. fn from_str_radix(s: &str, radix: u32) -> Result<Ratio<T>, ParseRatioError> {
  407. let split: Vec<&str> = s.splitn(2, '/').collect();
  408. if split.len() < 2 {
  409. Err(ParseRatioError { kind: RatioErrorKind::ParseError })
  410. } else {
  411. let a_result: Result<T, _> = T::from_str_radix(split[0], radix).map_err(|_| {
  412. ParseRatioError { kind: RatioErrorKind::ParseError }
  413. });
  414. a_result.and_then(|a| {
  415. let b_result: Result<T, _> = T::from_str_radix(split[1], radix).map_err(|_| {
  416. ParseRatioError { kind: RatioErrorKind::ParseError }
  417. });
  418. b_result.and_then(|b| {
  419. if b.is_zero() {
  420. Err(ParseRatioError { kind: RatioErrorKind::ZeroDenominator })
  421. } else {
  422. Ok(Ratio::new(a.clone(), b.clone()))
  423. }
  424. })
  425. })
  426. }
  427. }
  428. }
  429. impl<T: Clone + Integer + Signed> Signed for Ratio<T> {
  430. #[inline]
  431. fn abs(&self) -> Ratio<T> {
  432. if self.is_negative() {
  433. -self.clone()
  434. } else {
  435. self.clone()
  436. }
  437. }
  438. #[inline]
  439. fn abs_sub(&self, other: &Ratio<T>) -> Ratio<T> {
  440. if *self <= *other {
  441. Zero::zero()
  442. } else {
  443. self - other
  444. }
  445. }
  446. #[inline]
  447. fn signum(&self) -> Ratio<T> {
  448. if self.is_positive() {
  449. Self::one()
  450. } else if self.is_zero() {
  451. Self::zero()
  452. } else {
  453. -Self::one()
  454. }
  455. }
  456. #[inline]
  457. fn is_positive(&self) -> bool {
  458. !self.is_negative()
  459. }
  460. #[inline]
  461. fn is_negative(&self) -> bool {
  462. self.numer.is_negative() ^ self.denom.is_negative()
  463. }
  464. }
  465. // String conversions
  466. impl<T> fmt::Display for Ratio<T>
  467. where T: fmt::Display + Eq + One
  468. {
  469. /// Renders as `numer/denom`. If denom=1, renders as numer.
  470. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  471. if self.denom == One::one() {
  472. write!(f, "{}", self.numer)
  473. } else {
  474. write!(f, "{}/{}", self.numer, self.denom)
  475. }
  476. }
  477. }
  478. impl<T: FromStr + Clone + Integer> FromStr for Ratio<T> {
  479. type Err = ParseRatioError;
  480. /// Parses `numer/denom` or just `numer`.
  481. fn from_str(s: &str) -> Result<Ratio<T>, ParseRatioError> {
  482. let mut split = s.splitn(2, '/');
  483. let n = try!(split.next().ok_or(ParseRatioError { kind: RatioErrorKind::ParseError }));
  484. let num = try!(FromStr::from_str(n)
  485. .map_err(|_| ParseRatioError { kind: RatioErrorKind::ParseError }));
  486. let d = split.next().unwrap_or("1");
  487. let den = try!(FromStr::from_str(d)
  488. .map_err(|_| ParseRatioError { kind: RatioErrorKind::ParseError }));
  489. if Zero::is_zero(&den) {
  490. Err(ParseRatioError { kind: RatioErrorKind::ZeroDenominator })
  491. } else {
  492. Ok(Ratio::new(num, den))
  493. }
  494. }
  495. }
  496. #[cfg(feature = "serde")]
  497. impl<T> serde::Serialize for Ratio<T>
  498. where T: serde::Serialize + Clone + Integer + PartialOrd
  499. {
  500. fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
  501. where S: serde::Serializer
  502. {
  503. (self.numer(), self.denom()).serialize(serializer)
  504. }
  505. }
  506. #[cfg(feature = "serde")]
  507. impl<T> serde::Deserialize for Ratio<T>
  508. where T: serde::Deserialize + Clone + Integer + PartialOrd
  509. {
  510. fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
  511. where D: serde::Deserializer
  512. {
  513. let (numer, denom) = try!(serde::Deserialize::deserialize(deserializer));
  514. if denom == Zero::zero() {
  515. Err(serde::de::Error::invalid_value("denominator is zero"))
  516. } else {
  517. Ok(Ratio::new_raw(numer, denom))
  518. }
  519. }
  520. }
  521. // FIXME: Bubble up specific errors
  522. #[derive(Copy, Clone, Debug, PartialEq)]
  523. pub struct ParseRatioError {
  524. kind: RatioErrorKind,
  525. }
  526. #[derive(Copy, Clone, Debug, PartialEq)]
  527. enum RatioErrorKind {
  528. ParseError,
  529. ZeroDenominator,
  530. }
  531. impl fmt::Display for ParseRatioError {
  532. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  533. self.description().fmt(f)
  534. }
  535. }
  536. impl Error for ParseRatioError {
  537. fn description(&self) -> &str {
  538. self.kind.description()
  539. }
  540. }
  541. impl RatioErrorKind {
  542. fn description(&self) -> &'static str {
  543. match *self {
  544. RatioErrorKind::ParseError => "failed to parse integer",
  545. RatioErrorKind::ZeroDenominator => "zero value denominator",
  546. }
  547. }
  548. }
  549. #[cfg(test)]
  550. fn hash<T: hash::Hash>(x: &T) -> u64 {
  551. use std::hash::Hasher;
  552. let mut hasher = hash::SipHasher::new();
  553. x.hash(&mut hasher);
  554. hasher.finish()
  555. }
  556. #[cfg(test)]
  557. mod test {
  558. use super::{Ratio, Rational};
  559. #[cfg(feature = "num-bigint")]
  560. use super::BigRational;
  561. use std::str::FromStr;
  562. use std::i32;
  563. use traits::{Zero, One, Signed, FromPrimitive, Float};
  564. pub const _0: Rational = Ratio {
  565. numer: 0,
  566. denom: 1,
  567. };
  568. pub const _1: Rational = Ratio {
  569. numer: 1,
  570. denom: 1,
  571. };
  572. pub const _2: Rational = Ratio {
  573. numer: 2,
  574. denom: 1,
  575. };
  576. pub const _1_2: Rational = Ratio {
  577. numer: 1,
  578. denom: 2,
  579. };
  580. pub const _3_2: Rational = Ratio {
  581. numer: 3,
  582. denom: 2,
  583. };
  584. pub const _NEG1_2: Rational = Ratio {
  585. numer: -1,
  586. denom: 2,
  587. };
  588. pub const _1_3: Rational = Ratio {
  589. numer: 1,
  590. denom: 3,
  591. };
  592. pub const _NEG1_3: Rational = Ratio {
  593. numer: -1,
  594. denom: 3,
  595. };
  596. pub const _2_3: Rational = Ratio {
  597. numer: 2,
  598. denom: 3,
  599. };
  600. pub const _NEG2_3: Rational = Ratio {
  601. numer: -2,
  602. denom: 3,
  603. };
  604. #[cfg(feature = "num-bigint")]
  605. pub fn to_big(n: Rational) -> BigRational {
  606. Ratio::new(FromPrimitive::from_isize(n.numer).unwrap(),
  607. FromPrimitive::from_isize(n.denom).unwrap())
  608. }
  609. #[cfg(not(feature = "num-bigint"))]
  610. pub fn to_big(n: Rational) -> Rational {
  611. Ratio::new(FromPrimitive::from_isize(n.numer).unwrap(),
  612. FromPrimitive::from_isize(n.denom).unwrap())
  613. }
  614. #[test]
  615. fn test_test_constants() {
  616. // check our constants are what Ratio::new etc. would make.
  617. assert_eq!(_0, Zero::zero());
  618. assert_eq!(_1, One::one());
  619. assert_eq!(_2, Ratio::from_integer(2));
  620. assert_eq!(_1_2, Ratio::new(1, 2));
  621. assert_eq!(_3_2, Ratio::new(3, 2));
  622. assert_eq!(_NEG1_2, Ratio::new(-1, 2));
  623. }
  624. #[test]
  625. fn test_new_reduce() {
  626. let one22 = Ratio::new(2, 2);
  627. assert_eq!(one22, One::one());
  628. }
  629. #[test]
  630. #[should_panic]
  631. fn test_new_zero() {
  632. let _a = Ratio::new(1, 0);
  633. }
  634. #[test]
  635. fn test_cmp() {
  636. assert!(_0 == _0 && _1 == _1);
  637. assert!(_0 != _1 && _1 != _0);
  638. assert!(_0 < _1 && !(_1 < _0));
  639. assert!(_1 > _0 && !(_0 > _1));
  640. assert!(_0 <= _0 && _1 <= _1);
  641. assert!(_0 <= _1 && !(_1 <= _0));
  642. assert!(_0 >= _0 && _1 >= _1);
  643. assert!(_1 >= _0 && !(_0 >= _1));
  644. }
  645. #[test]
  646. fn test_cmp_overflow() {
  647. use std::cmp::Ordering;
  648. // issue #7 example:
  649. let big = Ratio::new(128u8, 1);
  650. let small = big.recip();
  651. assert!(big > small);
  652. // try a few that are closer together
  653. // (some matching numer, some matching denom, some neither)
  654. let ratios = vec![
  655. Ratio::new(125_i8, 127_i8),
  656. Ratio::new(63_i8, 64_i8),
  657. Ratio::new(124_i8, 125_i8),
  658. Ratio::new(125_i8, 126_i8),
  659. Ratio::new(126_i8, 127_i8),
  660. Ratio::new(127_i8, 126_i8),
  661. ];
  662. fn check_cmp(a: Ratio<i8>, b: Ratio<i8>, ord: Ordering) {
  663. println!("comparing {} and {}", a, b);
  664. assert_eq!(a.cmp(&b), ord);
  665. assert_eq!(b.cmp(&a), ord.reverse());
  666. }
  667. for (i, &a) in ratios.iter().enumerate() {
  668. check_cmp(a, a, Ordering::Equal);
  669. check_cmp(-a, a, Ordering::Less);
  670. for &b in &ratios[i + 1..] {
  671. check_cmp(a, b, Ordering::Less);
  672. check_cmp(-a, -b, Ordering::Greater);
  673. check_cmp(a.recip(), b.recip(), Ordering::Greater);
  674. check_cmp(-a.recip(), -b.recip(), Ordering::Less);
  675. }
  676. }
  677. }
  678. #[test]
  679. fn test_to_integer() {
  680. assert_eq!(_0.to_integer(), 0);
  681. assert_eq!(_1.to_integer(), 1);
  682. assert_eq!(_2.to_integer(), 2);
  683. assert_eq!(_1_2.to_integer(), 0);
  684. assert_eq!(_3_2.to_integer(), 1);
  685. assert_eq!(_NEG1_2.to_integer(), 0);
  686. }
  687. #[test]
  688. fn test_numer() {
  689. assert_eq!(_0.numer(), &0);
  690. assert_eq!(_1.numer(), &1);
  691. assert_eq!(_2.numer(), &2);
  692. assert_eq!(_1_2.numer(), &1);
  693. assert_eq!(_3_2.numer(), &3);
  694. assert_eq!(_NEG1_2.numer(), &(-1));
  695. }
  696. #[test]
  697. fn test_denom() {
  698. assert_eq!(_0.denom(), &1);
  699. assert_eq!(_1.denom(), &1);
  700. assert_eq!(_2.denom(), &1);
  701. assert_eq!(_1_2.denom(), &2);
  702. assert_eq!(_3_2.denom(), &2);
  703. assert_eq!(_NEG1_2.denom(), &2);
  704. }
  705. #[test]
  706. fn test_is_integer() {
  707. assert!(_0.is_integer());
  708. assert!(_1.is_integer());
  709. assert!(_2.is_integer());
  710. assert!(!_1_2.is_integer());
  711. assert!(!_3_2.is_integer());
  712. assert!(!_NEG1_2.is_integer());
  713. }
  714. #[test]
  715. fn test_show() {
  716. assert_eq!(format!("{}", _2), "2".to_string());
  717. assert_eq!(format!("{}", _1_2), "1/2".to_string());
  718. assert_eq!(format!("{}", _0), "0".to_string());
  719. assert_eq!(format!("{}", Ratio::from_integer(-2)), "-2".to_string());
  720. }
  721. mod arith {
  722. use super::{_0, _1, _2, _1_2, _3_2, _NEG1_2, to_big};
  723. use super::super::{Ratio, Rational};
  724. #[test]
  725. fn test_add() {
  726. fn test(a: Rational, b: Rational, c: Rational) {
  727. assert_eq!(a + b, c);
  728. assert_eq!(to_big(a) + to_big(b), to_big(c));
  729. }
  730. test(_1, _1_2, _3_2);
  731. test(_1, _1, _2);
  732. test(_1_2, _3_2, _2);
  733. test(_1_2, _NEG1_2, _0);
  734. }
  735. #[test]
  736. fn test_sub() {
  737. fn test(a: Rational, b: Rational, c: Rational) {
  738. assert_eq!(a - b, c);
  739. assert_eq!(to_big(a) - to_big(b), to_big(c))
  740. }
  741. test(_1, _1_2, _1_2);
  742. test(_3_2, _1_2, _1);
  743. test(_1, _NEG1_2, _3_2);
  744. }
  745. #[test]
  746. fn test_mul() {
  747. fn test(a: Rational, b: Rational, c: Rational) {
  748. assert_eq!(a * b, c);
  749. assert_eq!(to_big(a) * to_big(b), to_big(c))
  750. }
  751. test(_1, _1_2, _1_2);
  752. test(_1_2, _3_2, Ratio::new(3, 4));
  753. test(_1_2, _NEG1_2, Ratio::new(-1, 4));
  754. }
  755. #[test]
  756. fn test_div() {
  757. fn test(a: Rational, b: Rational, c: Rational) {
  758. assert_eq!(a / b, c);
  759. assert_eq!(to_big(a) / to_big(b), to_big(c))
  760. }
  761. test(_1, _1_2, _2);
  762. test(_3_2, _1_2, _1 + _2);
  763. test(_1, _NEG1_2, _NEG1_2 + _NEG1_2 + _NEG1_2 + _NEG1_2);
  764. }
  765. #[test]
  766. fn test_rem() {
  767. fn test(a: Rational, b: Rational, c: Rational) {
  768. assert_eq!(a % b, c);
  769. assert_eq!(to_big(a) % to_big(b), to_big(c))
  770. }
  771. test(_3_2, _1, _1_2);
  772. test(_2, _NEG1_2, _0);
  773. test(_1_2, _2, _1_2);
  774. }
  775. #[test]
  776. fn test_neg() {
  777. fn test(a: Rational, b: Rational) {
  778. assert_eq!(-a, b);
  779. assert_eq!(-to_big(a), to_big(b))
  780. }
  781. test(_0, _0);
  782. test(_1_2, _NEG1_2);
  783. test(-_1, _1);
  784. }
  785. #[test]
  786. fn test_zero() {
  787. assert_eq!(_0 + _0, _0);
  788. assert_eq!(_0 * _0, _0);
  789. assert_eq!(_0 * _1, _0);
  790. assert_eq!(_0 / _NEG1_2, _0);
  791. assert_eq!(_0 - _0, _0);
  792. }
  793. #[test]
  794. #[should_panic]
  795. fn test_div_0() {
  796. let _a = _1 / _0;
  797. }
  798. }
  799. #[test]
  800. fn test_round() {
  801. assert_eq!(_1_3.ceil(), _1);
  802. assert_eq!(_1_3.floor(), _0);
  803. assert_eq!(_1_3.round(), _0);
  804. assert_eq!(_1_3.trunc(), _0);
  805. assert_eq!(_NEG1_3.ceil(), _0);
  806. assert_eq!(_NEG1_3.floor(), -_1);
  807. assert_eq!(_NEG1_3.round(), _0);
  808. assert_eq!(_NEG1_3.trunc(), _0);
  809. assert_eq!(_2_3.ceil(), _1);
  810. assert_eq!(_2_3.floor(), _0);
  811. assert_eq!(_2_3.round(), _1);
  812. assert_eq!(_2_3.trunc(), _0);
  813. assert_eq!(_NEG2_3.ceil(), _0);
  814. assert_eq!(_NEG2_3.floor(), -_1);
  815. assert_eq!(_NEG2_3.round(), -_1);
  816. assert_eq!(_NEG2_3.trunc(), _0);
  817. assert_eq!(_1_2.ceil(), _1);
  818. assert_eq!(_1_2.floor(), _0);
  819. assert_eq!(_1_2.round(), _1);
  820. assert_eq!(_1_2.trunc(), _0);
  821. assert_eq!(_NEG1_2.ceil(), _0);
  822. assert_eq!(_NEG1_2.floor(), -_1);
  823. assert_eq!(_NEG1_2.round(), -_1);
  824. assert_eq!(_NEG1_2.trunc(), _0);
  825. assert_eq!(_1.ceil(), _1);
  826. assert_eq!(_1.floor(), _1);
  827. assert_eq!(_1.round(), _1);
  828. assert_eq!(_1.trunc(), _1);
  829. // Overflow checks
  830. let _neg1 = Ratio::from_integer(-1);
  831. let _large_rat1 = Ratio::new(i32::MAX, i32::MAX - 1);
  832. let _large_rat2 = Ratio::new(i32::MAX - 1, i32::MAX);
  833. let _large_rat3 = Ratio::new(i32::MIN + 2, i32::MIN + 1);
  834. let _large_rat4 = Ratio::new(i32::MIN + 1, i32::MIN + 2);
  835. let _large_rat5 = Ratio::new(i32::MIN + 2, i32::MAX);
  836. let _large_rat6 = Ratio::new(i32::MAX, i32::MIN + 2);
  837. let _large_rat7 = Ratio::new(1, i32::MIN + 1);
  838. let _large_rat8 = Ratio::new(1, i32::MAX);
  839. assert_eq!(_large_rat1.round(), One::one());
  840. assert_eq!(_large_rat2.round(), One::one());
  841. assert_eq!(_large_rat3.round(), One::one());
  842. assert_eq!(_large_rat4.round(), One::one());
  843. assert_eq!(_large_rat5.round(), _neg1);
  844. assert_eq!(_large_rat6.round(), _neg1);
  845. assert_eq!(_large_rat7.round(), Zero::zero());
  846. assert_eq!(_large_rat8.round(), Zero::zero());
  847. }
  848. #[test]
  849. fn test_fract() {
  850. assert_eq!(_1.fract(), _0);
  851. assert_eq!(_NEG1_2.fract(), _NEG1_2);
  852. assert_eq!(_1_2.fract(), _1_2);
  853. assert_eq!(_3_2.fract(), _1_2);
  854. }
  855. #[test]
  856. fn test_recip() {
  857. assert_eq!(_1 * _1.recip(), _1);
  858. assert_eq!(_2 * _2.recip(), _1);
  859. assert_eq!(_1_2 * _1_2.recip(), _1);
  860. assert_eq!(_3_2 * _3_2.recip(), _1);
  861. assert_eq!(_NEG1_2 * _NEG1_2.recip(), _1);
  862. }
  863. #[test]
  864. fn test_pow() {
  865. assert_eq!(_1_2.pow(2), Ratio::new(1, 4));
  866. assert_eq!(_1_2.pow(-2), Ratio::new(4, 1));
  867. assert_eq!(_1.pow(1), _1);
  868. assert_eq!(_NEG1_2.pow(2), _1_2.pow(2));
  869. assert_eq!(_NEG1_2.pow(3), -_1_2.pow(3));
  870. assert_eq!(_3_2.pow(0), _1);
  871. assert_eq!(_3_2.pow(-1), _3_2.recip());
  872. assert_eq!(_3_2.pow(3), Ratio::new(27, 8));
  873. }
  874. #[test]
  875. fn test_to_from_str() {
  876. fn test(r: Rational, s: String) {
  877. assert_eq!(FromStr::from_str(&s), Ok(r));
  878. assert_eq!(r.to_string(), s);
  879. }
  880. test(_1, "1".to_string());
  881. test(_0, "0".to_string());
  882. test(_1_2, "1/2".to_string());
  883. test(_3_2, "3/2".to_string());
  884. test(_2, "2".to_string());
  885. test(_NEG1_2, "-1/2".to_string());
  886. }
  887. #[test]
  888. fn test_from_str_fail() {
  889. fn test(s: &str) {
  890. let rational: Result<Rational, _> = FromStr::from_str(s);
  891. assert!(rational.is_err());
  892. }
  893. let xs = ["0 /1", "abc", "", "1/", "--1/2", "3/2/1", "1/0"];
  894. for &s in xs.iter() {
  895. test(s);
  896. }
  897. }
  898. #[cfg(feature = "num-bigint")]
  899. #[test]
  900. fn test_from_float() {
  901. fn test<T: Float>(given: T, (numer, denom): (&str, &str)) {
  902. let ratio: BigRational = Ratio::from_float(given).unwrap();
  903. assert_eq!(ratio,
  904. Ratio::new(FromStr::from_str(numer).unwrap(),
  905. FromStr::from_str(denom).unwrap()));
  906. }
  907. // f32
  908. test(3.14159265359f32, ("13176795", "4194304"));
  909. test(2f32.powf(100.), ("1267650600228229401496703205376", "1"));
  910. test(-2f32.powf(100.), ("-1267650600228229401496703205376", "1"));
  911. test(1.0 / 2f32.powf(100.),
  912. ("1", "1267650600228229401496703205376"));
  913. test(684729.48391f32, ("1369459", "2"));
  914. test(-8573.5918555f32, ("-4389679", "512"));
  915. // f64
  916. test(3.14159265359f64, ("3537118876014453", "1125899906842624"));
  917. test(2f64.powf(100.), ("1267650600228229401496703205376", "1"));
  918. test(-2f64.powf(100.), ("-1267650600228229401496703205376", "1"));
  919. test(684729.48391f64, ("367611342500051", "536870912"));
  920. test(-8573.5918555f64, ("-4713381968463931", "549755813888"));
  921. test(1.0 / 2f64.powf(100.),
  922. ("1", "1267650600228229401496703205376"));
  923. }
  924. #[cfg(feature = "num-bigint")]
  925. #[test]
  926. fn test_from_float_fail() {
  927. use std::{f32, f64};
  928. assert_eq!(Ratio::from_float(f32::NAN), None);
  929. assert_eq!(Ratio::from_float(f32::INFINITY), None);
  930. assert_eq!(Ratio::from_float(f32::NEG_INFINITY), None);
  931. assert_eq!(Ratio::from_float(f64::NAN), None);
  932. assert_eq!(Ratio::from_float(f64::INFINITY), None);
  933. assert_eq!(Ratio::from_float(f64::NEG_INFINITY), None);
  934. }
  935. #[test]
  936. fn test_signed() {
  937. assert_eq!(_NEG1_2.abs(), _1_2);
  938. assert_eq!(_3_2.abs_sub(&_1_2), _1);
  939. assert_eq!(_1_2.abs_sub(&_3_2), Zero::zero());
  940. assert_eq!(_1_2.signum(), One::one());
  941. assert_eq!(_NEG1_2.signum(), -<Ratio<isize>>::one());
  942. assert!(_NEG1_2.is_negative());
  943. assert!(!_NEG1_2.is_positive());
  944. assert!(!_1_2.is_negative());
  945. }
  946. #[test]
  947. fn test_hash() {
  948. assert!(::hash(&_0) != ::hash(&_1));
  949. assert!(::hash(&_0) != ::hash(&_3_2));
  950. }
  951. }