lib.rs 34 KB

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