lib.rs 33 KB

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