lib.rs 33 KB

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