lib.rs 42 KB

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