lib.rs 41 KB

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