lib.rs 33 KB

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