lib.rs 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382
  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::Hasher;
  730. let mut hasher = hash::SipHasher::new();
  731. x.hash(&mut hasher);
  732. hasher.finish()
  733. }
  734. #[cfg(test)]
  735. mod test {
  736. use super::{Ratio, Rational};
  737. #[cfg(feature = "num-bigint")]
  738. use super::BigRational;
  739. use std::str::FromStr;
  740. use std::i32;
  741. use std::f64;
  742. use traits::{Zero, One, Signed, FromPrimitive, Float};
  743. pub const _0: Rational = Ratio {
  744. numer: 0,
  745. denom: 1,
  746. };
  747. pub const _1: Rational = Ratio {
  748. numer: 1,
  749. denom: 1,
  750. };
  751. pub const _2: Rational = Ratio {
  752. numer: 2,
  753. denom: 1,
  754. };
  755. pub const _NEG2: Rational = Ratio {
  756. numer: -2,
  757. denom: 1,
  758. };
  759. pub const _1_2: Rational = Ratio {
  760. numer: 1,
  761. denom: 2,
  762. };
  763. pub const _3_2: Rational = Ratio {
  764. numer: 3,
  765. denom: 2,
  766. };
  767. pub const _NEG1_2: Rational = Ratio {
  768. numer: -1,
  769. denom: 2,
  770. };
  771. pub const _1_NEG2: Rational = Ratio {
  772. numer: 1,
  773. denom: -2,
  774. };
  775. pub const _NEG1_NEG2: Rational = Ratio {
  776. numer: -1,
  777. denom: -2,
  778. };
  779. pub const _1_3: Rational = Ratio {
  780. numer: 1,
  781. denom: 3,
  782. };
  783. pub const _NEG1_3: Rational = Ratio {
  784. numer: -1,
  785. denom: 3,
  786. };
  787. pub const _2_3: Rational = Ratio {
  788. numer: 2,
  789. denom: 3,
  790. };
  791. pub const _NEG2_3: Rational = Ratio {
  792. numer: -2,
  793. denom: 3,
  794. };
  795. #[cfg(feature = "num-bigint")]
  796. pub fn to_big(n: Rational) -> BigRational {
  797. Ratio::new(FromPrimitive::from_isize(n.numer).unwrap(),
  798. FromPrimitive::from_isize(n.denom).unwrap())
  799. }
  800. #[cfg(not(feature = "num-bigint"))]
  801. pub fn to_big(n: Rational) -> Rational {
  802. Ratio::new(FromPrimitive::from_isize(n.numer).unwrap(),
  803. FromPrimitive::from_isize(n.denom).unwrap())
  804. }
  805. #[test]
  806. fn test_test_constants() {
  807. // check our constants are what Ratio::new etc. would make.
  808. assert_eq!(_0, Zero::zero());
  809. assert_eq!(_1, One::one());
  810. assert_eq!(_2, Ratio::from_integer(2));
  811. assert_eq!(_1_2, Ratio::new(1, 2));
  812. assert_eq!(_3_2, Ratio::new(3, 2));
  813. assert_eq!(_NEG1_2, Ratio::new(-1, 2));
  814. assert_eq!(_2, From::from(2));
  815. }
  816. #[test]
  817. fn test_new_reduce() {
  818. let one22 = Ratio::new(2, 2);
  819. assert_eq!(one22, One::one());
  820. }
  821. #[test]
  822. #[should_panic]
  823. fn test_new_zero() {
  824. let _a = Ratio::new(1, 0);
  825. }
  826. #[test]
  827. fn test_approximate_float() {
  828. assert_eq!(Ratio::from_f32(0.5f32), Some(Ratio::new(1i64, 2)));
  829. assert_eq!(Ratio::from_f64(0.5f64), Some(Ratio::new(1i32, 2)));
  830. assert_eq!(Ratio::from_f32(5f32), Some(Ratio::new(5i64, 1)));
  831. assert_eq!(Ratio::from_f64(5f64), Some(Ratio::new(5i32, 1)));
  832. assert_eq!(Ratio::from_f32(29.97f32), Some(Ratio::new(2997i64, 100)));
  833. assert_eq!(Ratio::from_f32(-29.97f32), Some(Ratio::new(-2997i64, 100)));
  834. assert_eq!(Ratio::<i8>::from_f32(63.5f32), Some(Ratio::new(127i8, 2)));
  835. assert_eq!(Ratio::<i8>::from_f32(126.5f32), Some(Ratio::new(126i8, 1)));
  836. assert_eq!(Ratio::<i8>::from_f32(127.0f32), Some(Ratio::new(127i8, 1)));
  837. assert_eq!(Ratio::<i8>::from_f32(127.5f32), None);
  838. assert_eq!(Ratio::<i8>::from_f32(-63.5f32), Some(Ratio::new(-127i8, 2)));
  839. assert_eq!(Ratio::<i8>::from_f32(-126.5f32), Some(Ratio::new(-126i8, 1)));
  840. assert_eq!(Ratio::<i8>::from_f32(-127.0f32), Some(Ratio::new(-127i8, 1)));
  841. assert_eq!(Ratio::<i8>::from_f32(-127.5f32), None);
  842. assert_eq!(Ratio::<u8>::from_f32(-127f32), None);
  843. assert_eq!(Ratio::<u8>::from_f32(127f32), Some(Ratio::new(127u8, 1)));
  844. assert_eq!(Ratio::<u8>::from_f32(127.5f32), Some(Ratio::new(255u8, 2)));
  845. assert_eq!(Ratio::<u8>::from_f32(256f32), None);
  846. assert_eq!(Ratio::<i64>::from_f64(-10e200), None);
  847. assert_eq!(Ratio::<i64>::from_f64(10e200), None);
  848. assert_eq!(Ratio::<i64>::from_f64(f64::INFINITY), None);
  849. assert_eq!(Ratio::<i64>::from_f64(f64::NEG_INFINITY), None);
  850. assert_eq!(Ratio::<i64>::from_f64(f64::NAN), None);
  851. assert_eq!(Ratio::<i64>::from_f64(f64::EPSILON), Some(Ratio::new(1, 4503599627370496)));
  852. assert_eq!(Ratio::<i64>::from_f64(0.0), Some(Ratio::new(0, 1)));
  853. assert_eq!(Ratio::<i64>::from_f64(-0.0), Some(Ratio::new(0, 1)));
  854. }
  855. #[test]
  856. fn test_cmp() {
  857. assert!(_0 == _0 && _1 == _1);
  858. assert!(_0 != _1 && _1 != _0);
  859. assert!(_0 < _1 && !(_1 < _0));
  860. assert!(_1 > _0 && !(_0 > _1));
  861. assert!(_0 <= _0 && _1 <= _1);
  862. assert!(_0 <= _1 && !(_1 <= _0));
  863. assert!(_0 >= _0 && _1 >= _1);
  864. assert!(_1 >= _0 && !(_0 >= _1));
  865. }
  866. #[test]
  867. fn test_cmp_overflow() {
  868. use std::cmp::Ordering;
  869. // issue #7 example:
  870. let big = Ratio::new(128u8, 1);
  871. let small = big.recip();
  872. assert!(big > small);
  873. // try a few that are closer together
  874. // (some matching numer, some matching denom, some neither)
  875. let ratios = vec![
  876. Ratio::new(125_i8, 127_i8),
  877. Ratio::new(63_i8, 64_i8),
  878. Ratio::new(124_i8, 125_i8),
  879. Ratio::new(125_i8, 126_i8),
  880. Ratio::new(126_i8, 127_i8),
  881. Ratio::new(127_i8, 126_i8),
  882. ];
  883. fn check_cmp(a: Ratio<i8>, b: Ratio<i8>, ord: Ordering) {
  884. println!("comparing {} and {}", a, b);
  885. assert_eq!(a.cmp(&b), ord);
  886. assert_eq!(b.cmp(&a), ord.reverse());
  887. }
  888. for (i, &a) in ratios.iter().enumerate() {
  889. check_cmp(a, a, Ordering::Equal);
  890. check_cmp(-a, a, Ordering::Less);
  891. for &b in &ratios[i + 1..] {
  892. check_cmp(a, b, Ordering::Less);
  893. check_cmp(-a, -b, Ordering::Greater);
  894. check_cmp(a.recip(), b.recip(), Ordering::Greater);
  895. check_cmp(-a.recip(), -b.recip(), Ordering::Less);
  896. }
  897. }
  898. }
  899. #[test]
  900. fn test_to_integer() {
  901. assert_eq!(_0.to_integer(), 0);
  902. assert_eq!(_1.to_integer(), 1);
  903. assert_eq!(_2.to_integer(), 2);
  904. assert_eq!(_1_2.to_integer(), 0);
  905. assert_eq!(_3_2.to_integer(), 1);
  906. assert_eq!(_NEG1_2.to_integer(), 0);
  907. }
  908. #[test]
  909. fn test_numer() {
  910. assert_eq!(_0.numer(), &0);
  911. assert_eq!(_1.numer(), &1);
  912. assert_eq!(_2.numer(), &2);
  913. assert_eq!(_1_2.numer(), &1);
  914. assert_eq!(_3_2.numer(), &3);
  915. assert_eq!(_NEG1_2.numer(), &(-1));
  916. }
  917. #[test]
  918. fn test_denom() {
  919. assert_eq!(_0.denom(), &1);
  920. assert_eq!(_1.denom(), &1);
  921. assert_eq!(_2.denom(), &1);
  922. assert_eq!(_1_2.denom(), &2);
  923. assert_eq!(_3_2.denom(), &2);
  924. assert_eq!(_NEG1_2.denom(), &2);
  925. }
  926. #[test]
  927. fn test_is_integer() {
  928. assert!(_0.is_integer());
  929. assert!(_1.is_integer());
  930. assert!(_2.is_integer());
  931. assert!(!_1_2.is_integer());
  932. assert!(!_3_2.is_integer());
  933. assert!(!_NEG1_2.is_integer());
  934. }
  935. #[test]
  936. fn test_show() {
  937. assert_eq!(format!("{}", _2), "2".to_string());
  938. assert_eq!(format!("{}", _1_2), "1/2".to_string());
  939. assert_eq!(format!("{}", _0), "0".to_string());
  940. assert_eq!(format!("{}", Ratio::from_integer(-2)), "-2".to_string());
  941. }
  942. mod arith {
  943. use super::{_0, _1, _2, _1_2, _3_2, _NEG1_2, to_big};
  944. use super::super::{Ratio, Rational};
  945. #[test]
  946. fn test_add() {
  947. fn test(a: Rational, b: Rational, c: Rational) {
  948. assert_eq!(a + b, c);
  949. assert_eq!(to_big(a) + to_big(b), to_big(c));
  950. }
  951. test(_1, _1_2, _3_2);
  952. test(_1, _1, _2);
  953. test(_1_2, _3_2, _2);
  954. test(_1_2, _NEG1_2, _0);
  955. }
  956. #[test]
  957. fn test_sub() {
  958. fn test(a: Rational, b: Rational, c: Rational) {
  959. assert_eq!(a - b, c);
  960. assert_eq!(to_big(a) - to_big(b), to_big(c))
  961. }
  962. test(_1, _1_2, _1_2);
  963. test(_3_2, _1_2, _1);
  964. test(_1, _NEG1_2, _3_2);
  965. }
  966. #[test]
  967. fn test_mul() {
  968. fn test(a: Rational, b: Rational, c: Rational) {
  969. assert_eq!(a * b, c);
  970. assert_eq!(to_big(a) * to_big(b), to_big(c))
  971. }
  972. test(_1, _1_2, _1_2);
  973. test(_1_2, _3_2, Ratio::new(3, 4));
  974. test(_1_2, _NEG1_2, Ratio::new(-1, 4));
  975. }
  976. #[test]
  977. fn test_div() {
  978. fn test(a: Rational, b: Rational, c: Rational) {
  979. assert_eq!(a / b, c);
  980. assert_eq!(to_big(a) / to_big(b), to_big(c))
  981. }
  982. test(_1, _1_2, _2);
  983. test(_3_2, _1_2, _1 + _2);
  984. test(_1, _NEG1_2, _NEG1_2 + _NEG1_2 + _NEG1_2 + _NEG1_2);
  985. }
  986. #[test]
  987. fn test_rem() {
  988. fn test(a: Rational, b: Rational, c: Rational) {
  989. assert_eq!(a % b, c);
  990. assert_eq!(to_big(a) % to_big(b), to_big(c))
  991. }
  992. test(_3_2, _1, _1_2);
  993. test(_2, _NEG1_2, _0);
  994. test(_1_2, _2, _1_2);
  995. }
  996. #[test]
  997. fn test_neg() {
  998. fn test(a: Rational, b: Rational) {
  999. assert_eq!(-a, b);
  1000. assert_eq!(-to_big(a), to_big(b))
  1001. }
  1002. test(_0, _0);
  1003. test(_1_2, _NEG1_2);
  1004. test(-_1, _1);
  1005. }
  1006. #[test]
  1007. fn test_zero() {
  1008. assert_eq!(_0 + _0, _0);
  1009. assert_eq!(_0 * _0, _0);
  1010. assert_eq!(_0 * _1, _0);
  1011. assert_eq!(_0 / _NEG1_2, _0);
  1012. assert_eq!(_0 - _0, _0);
  1013. }
  1014. #[test]
  1015. #[should_panic]
  1016. fn test_div_0() {
  1017. let _a = _1 / _0;
  1018. }
  1019. }
  1020. #[test]
  1021. fn test_round() {
  1022. assert_eq!(_1_3.ceil(), _1);
  1023. assert_eq!(_1_3.floor(), _0);
  1024. assert_eq!(_1_3.round(), _0);
  1025. assert_eq!(_1_3.trunc(), _0);
  1026. assert_eq!(_NEG1_3.ceil(), _0);
  1027. assert_eq!(_NEG1_3.floor(), -_1);
  1028. assert_eq!(_NEG1_3.round(), _0);
  1029. assert_eq!(_NEG1_3.trunc(), _0);
  1030. assert_eq!(_2_3.ceil(), _1);
  1031. assert_eq!(_2_3.floor(), _0);
  1032. assert_eq!(_2_3.round(), _1);
  1033. assert_eq!(_2_3.trunc(), _0);
  1034. assert_eq!(_NEG2_3.ceil(), _0);
  1035. assert_eq!(_NEG2_3.floor(), -_1);
  1036. assert_eq!(_NEG2_3.round(), -_1);
  1037. assert_eq!(_NEG2_3.trunc(), _0);
  1038. assert_eq!(_1_2.ceil(), _1);
  1039. assert_eq!(_1_2.floor(), _0);
  1040. assert_eq!(_1_2.round(), _1);
  1041. assert_eq!(_1_2.trunc(), _0);
  1042. assert_eq!(_NEG1_2.ceil(), _0);
  1043. assert_eq!(_NEG1_2.floor(), -_1);
  1044. assert_eq!(_NEG1_2.round(), -_1);
  1045. assert_eq!(_NEG1_2.trunc(), _0);
  1046. assert_eq!(_1.ceil(), _1);
  1047. assert_eq!(_1.floor(), _1);
  1048. assert_eq!(_1.round(), _1);
  1049. assert_eq!(_1.trunc(), _1);
  1050. // Overflow checks
  1051. let _neg1 = Ratio::from_integer(-1);
  1052. let _large_rat1 = Ratio::new(i32::MAX, i32::MAX - 1);
  1053. let _large_rat2 = Ratio::new(i32::MAX - 1, i32::MAX);
  1054. let _large_rat3 = Ratio::new(i32::MIN + 2, i32::MIN + 1);
  1055. let _large_rat4 = Ratio::new(i32::MIN + 1, i32::MIN + 2);
  1056. let _large_rat5 = Ratio::new(i32::MIN + 2, i32::MAX);
  1057. let _large_rat6 = Ratio::new(i32::MAX, i32::MIN + 2);
  1058. let _large_rat7 = Ratio::new(1, i32::MIN + 1);
  1059. let _large_rat8 = Ratio::new(1, i32::MAX);
  1060. assert_eq!(_large_rat1.round(), One::one());
  1061. assert_eq!(_large_rat2.round(), One::one());
  1062. assert_eq!(_large_rat3.round(), One::one());
  1063. assert_eq!(_large_rat4.round(), One::one());
  1064. assert_eq!(_large_rat5.round(), _neg1);
  1065. assert_eq!(_large_rat6.round(), _neg1);
  1066. assert_eq!(_large_rat7.round(), Zero::zero());
  1067. assert_eq!(_large_rat8.round(), Zero::zero());
  1068. }
  1069. #[test]
  1070. fn test_fract() {
  1071. assert_eq!(_1.fract(), _0);
  1072. assert_eq!(_NEG1_2.fract(), _NEG1_2);
  1073. assert_eq!(_1_2.fract(), _1_2);
  1074. assert_eq!(_3_2.fract(), _1_2);
  1075. }
  1076. #[test]
  1077. fn test_recip() {
  1078. assert_eq!(_1 * _1.recip(), _1);
  1079. assert_eq!(_2 * _2.recip(), _1);
  1080. assert_eq!(_1_2 * _1_2.recip(), _1);
  1081. assert_eq!(_3_2 * _3_2.recip(), _1);
  1082. assert_eq!(_NEG1_2 * _NEG1_2.recip(), _1);
  1083. assert_eq!(_3_2.recip(), _2_3);
  1084. assert_eq!(_NEG1_2.recip(), _NEG2);
  1085. assert_eq!(_NEG1_2.recip().denom(), &1);
  1086. }
  1087. #[test]
  1088. #[should_panic(expected = "== 0")]
  1089. fn test_recip_fail() {
  1090. let _a = Ratio::new(0, 1).recip();
  1091. }
  1092. #[test]
  1093. fn test_pow() {
  1094. assert_eq!(_1_2.pow(2), Ratio::new(1, 4));
  1095. assert_eq!(_1_2.pow(-2), Ratio::new(4, 1));
  1096. assert_eq!(_1.pow(1), _1);
  1097. assert_eq!(_NEG1_2.pow(2), _1_2.pow(2));
  1098. assert_eq!(_NEG1_2.pow(3), -_1_2.pow(3));
  1099. assert_eq!(_3_2.pow(0), _1);
  1100. assert_eq!(_3_2.pow(-1), _3_2.recip());
  1101. assert_eq!(_3_2.pow(3), Ratio::new(27, 8));
  1102. }
  1103. #[test]
  1104. fn test_to_from_str() {
  1105. fn test(r: Rational, s: String) {
  1106. assert_eq!(FromStr::from_str(&s), Ok(r));
  1107. assert_eq!(r.to_string(), s);
  1108. }
  1109. test(_1, "1".to_string());
  1110. test(_0, "0".to_string());
  1111. test(_1_2, "1/2".to_string());
  1112. test(_3_2, "3/2".to_string());
  1113. test(_2, "2".to_string());
  1114. test(_NEG1_2, "-1/2".to_string());
  1115. }
  1116. #[test]
  1117. fn test_from_str_fail() {
  1118. fn test(s: &str) {
  1119. let rational: Result<Rational, _> = FromStr::from_str(s);
  1120. assert!(rational.is_err());
  1121. }
  1122. let xs = ["0 /1", "abc", "", "1/", "--1/2", "3/2/1", "1/0"];
  1123. for &s in xs.iter() {
  1124. test(s);
  1125. }
  1126. }
  1127. #[cfg(feature = "num-bigint")]
  1128. #[test]
  1129. fn test_from_float() {
  1130. fn test<T: Float>(given: T, (numer, denom): (&str, &str)) {
  1131. let ratio: BigRational = Ratio::from_float(given).unwrap();
  1132. assert_eq!(ratio,
  1133. Ratio::new(FromStr::from_str(numer).unwrap(),
  1134. FromStr::from_str(denom).unwrap()));
  1135. }
  1136. // f32
  1137. test(3.14159265359f32, ("13176795", "4194304"));
  1138. test(2f32.powf(100.), ("1267650600228229401496703205376", "1"));
  1139. test(-2f32.powf(100.), ("-1267650600228229401496703205376", "1"));
  1140. test(1.0 / 2f32.powf(100.),
  1141. ("1", "1267650600228229401496703205376"));
  1142. test(684729.48391f32, ("1369459", "2"));
  1143. test(-8573.5918555f32, ("-4389679", "512"));
  1144. // f64
  1145. test(3.14159265359f64, ("3537118876014453", "1125899906842624"));
  1146. test(2f64.powf(100.), ("1267650600228229401496703205376", "1"));
  1147. test(-2f64.powf(100.), ("-1267650600228229401496703205376", "1"));
  1148. test(684729.48391f64, ("367611342500051", "536870912"));
  1149. test(-8573.5918555f64, ("-4713381968463931", "549755813888"));
  1150. test(1.0 / 2f64.powf(100.),
  1151. ("1", "1267650600228229401496703205376"));
  1152. }
  1153. #[cfg(feature = "num-bigint")]
  1154. #[test]
  1155. fn test_from_float_fail() {
  1156. use std::{f32, f64};
  1157. assert_eq!(Ratio::from_float(f32::NAN), None);
  1158. assert_eq!(Ratio::from_float(f32::INFINITY), None);
  1159. assert_eq!(Ratio::from_float(f32::NEG_INFINITY), None);
  1160. assert_eq!(Ratio::from_float(f64::NAN), None);
  1161. assert_eq!(Ratio::from_float(f64::INFINITY), None);
  1162. assert_eq!(Ratio::from_float(f64::NEG_INFINITY), None);
  1163. }
  1164. #[test]
  1165. fn test_signed() {
  1166. assert_eq!(_NEG1_2.abs(), _1_2);
  1167. assert_eq!(_3_2.abs_sub(&_1_2), _1);
  1168. assert_eq!(_1_2.abs_sub(&_3_2), Zero::zero());
  1169. assert_eq!(_1_2.signum(), One::one());
  1170. assert_eq!(_NEG1_2.signum(), -<Ratio<isize>>::one());
  1171. assert_eq!(_0.signum(), Zero::zero());
  1172. assert!(_NEG1_2.is_negative());
  1173. assert!(_1_NEG2.is_negative());
  1174. assert!(!_NEG1_2.is_positive());
  1175. assert!(!_1_NEG2.is_positive());
  1176. assert!(_1_2.is_positive());
  1177. assert!(_NEG1_NEG2.is_positive());
  1178. assert!(!_1_2.is_negative());
  1179. assert!(!_NEG1_NEG2.is_negative());
  1180. assert!(!_0.is_positive());
  1181. assert!(!_0.is_negative());
  1182. }
  1183. #[test]
  1184. fn test_hash() {
  1185. assert!(::hash(&_0) != ::hash(&_1));
  1186. assert!(::hash(&_0) != ::hash(&_3_2));
  1187. }
  1188. #[test]
  1189. fn test_into_pair() {
  1190. assert_eq! ((0, 1), _0.into());
  1191. assert_eq! ((-2, 1), _NEG2.into());
  1192. assert_eq! ((1, -2), _1_NEG2.into());
  1193. }
  1194. #[test]
  1195. fn test_from_pair() {
  1196. assert_eq! (_0, Ratio::from ((0, 1)));
  1197. assert_eq! (_1, Ratio::from ((1, 1)));
  1198. assert_eq! (_NEG2, Ratio::from ((-2, 1)));
  1199. assert_eq! (_1_NEG2, Ratio::from ((1, -2)));
  1200. }
  1201. }