rational.rs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  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. use Integer;
  12. use std::cmp;
  13. use std::fmt;
  14. use std::str::FromStr;
  15. use std::num::{FromStrRadix, Float};
  16. use std::iter::{AdditiveIterator, MultiplicativeIterator};
  17. use bigint::{BigInt, BigUint, Sign};
  18. use {Num, Signed, Zero, One};
  19. /// Represents the ratio between 2 numbers.
  20. #[deriving(Clone, Hash, Encodable, Decodable)]
  21. #[allow(missing_docs)]
  22. pub struct Ratio<T> {
  23. numer: T,
  24. denom: T
  25. }
  26. /// Alias for a `Ratio` of machine-sized integers.
  27. pub type Rational = Ratio<int>;
  28. pub type Rational32 = Ratio<i32>;
  29. pub type Rational64 = Ratio<i64>;
  30. /// Alias for arbitrary precision rationals.
  31. pub type BigRational = Ratio<BigInt>;
  32. impl<T: Clone + Integer + PartialOrd>
  33. Ratio<T> {
  34. /// Creates a ratio representing the integer `t`.
  35. #[inline]
  36. pub fn from_integer(t: T) -> Ratio<T> {
  37. Ratio::new_raw(t, One::one())
  38. }
  39. /// Creates a ratio without checking for `denom == 0` or reducing.
  40. #[inline]
  41. pub fn new_raw(numer: T, denom: T) -> Ratio<T> {
  42. Ratio { numer: numer, denom: denom }
  43. }
  44. /// Create a new Ratio. Fails if `denom == 0`.
  45. #[inline]
  46. pub fn new(numer: T, denom: T) -> Ratio<T> {
  47. if denom == Zero::zero() {
  48. panic!("denominator == 0");
  49. }
  50. let mut ret = Ratio::new_raw(numer, denom);
  51. ret.reduce();
  52. ret
  53. }
  54. /// Converts to an integer.
  55. #[inline]
  56. pub fn to_integer(&self) -> T {
  57. self.trunc().numer
  58. }
  59. /// Gets an immutable reference to the numerator.
  60. #[inline]
  61. pub fn numer<'a>(&'a self) -> &'a T {
  62. &self.numer
  63. }
  64. /// Gets an immutable reference to the denominator.
  65. #[inline]
  66. pub fn denom<'a>(&'a self) -> &'a T {
  67. &self.denom
  68. }
  69. /// Returns true if the rational number is an integer (denominator is 1).
  70. #[inline]
  71. pub fn is_integer(&self) -> bool {
  72. self.denom == One::one()
  73. }
  74. /// Put self into lowest terms, with denom > 0.
  75. fn reduce(&mut self) {
  76. let g : T = self.numer.gcd(&self.denom);
  77. // FIXME(#5992): assignment operator overloads
  78. // self.numer /= g;
  79. self.numer = self.numer / g;
  80. // FIXME(#5992): assignment operator overloads
  81. // self.denom /= g;
  82. self.denom = self.denom / g;
  83. // keep denom positive!
  84. if self.denom < Zero::zero() {
  85. self.numer = -self.numer;
  86. self.denom = -self.denom;
  87. }
  88. }
  89. /// Returns a `reduce`d copy of self.
  90. pub fn reduced(&self) -> Ratio<T> {
  91. let mut ret = self.clone();
  92. ret.reduce();
  93. ret
  94. }
  95. /// Returns the reciprocal.
  96. #[inline]
  97. pub fn recip(&self) -> Ratio<T> {
  98. Ratio::new_raw(self.denom.clone(), self.numer.clone())
  99. }
  100. /// Rounds towards minus infinity.
  101. #[inline]
  102. pub fn floor(&self) -> Ratio<T> {
  103. if *self < Zero::zero() {
  104. Ratio::from_integer((self.numer - self.denom + One::one()) / self.denom)
  105. } else {
  106. Ratio::from_integer(self.numer / self.denom)
  107. }
  108. }
  109. /// Rounds towards plus infinity.
  110. #[inline]
  111. pub fn ceil(&self) -> Ratio<T> {
  112. if *self < Zero::zero() {
  113. Ratio::from_integer(self.numer / self.denom)
  114. } else {
  115. Ratio::from_integer((self.numer + self.denom - One::one()) / self.denom)
  116. }
  117. }
  118. /// Rounds to the nearest integer. Rounds half-way cases away from zero.
  119. #[inline]
  120. pub fn round(&self) -> Ratio<T> {
  121. let one: T = One::one();
  122. let two: T = one + one;
  123. // Find unsigned fractional part of rational number
  124. let fractional = self.fract().abs();
  125. // The algorithm compares the unsigned fractional part with 1/2, that
  126. // is, a/b >= 1/2, or a >= b/2. For odd denominators, we use
  127. // a >= (b/2)+1. This avoids overflow issues.
  128. let half_or_larger = if fractional.denom().is_even() {
  129. *fractional.numer() >= *fractional.denom() / two
  130. } else {
  131. *fractional.numer() >= (*fractional.denom() / two) + one
  132. };
  133. if half_or_larger {
  134. if *self >= Zero::zero() {
  135. self.trunc() + One::one()
  136. } else {
  137. self.trunc() - One::one()
  138. }
  139. } else {
  140. self.trunc()
  141. }
  142. }
  143. /// Rounds towards zero.
  144. #[inline]
  145. pub fn trunc(&self) -> Ratio<T> {
  146. Ratio::from_integer(self.numer / self.denom)
  147. }
  148. /// Returns the fractional part of a number.
  149. #[inline]
  150. pub fn fract(&self) -> Ratio<T> {
  151. Ratio::new_raw(self.numer % self.denom, self.denom.clone())
  152. }
  153. }
  154. impl Ratio<BigInt> {
  155. /// Converts a float into a rational number.
  156. pub fn from_float<T: Float>(f: T) -> Option<BigRational> {
  157. if !f.is_finite() {
  158. return None;
  159. }
  160. let (mantissa, exponent, sign) = f.integer_decode();
  161. let bigint_sign = if sign == 1 { Sign::Plus } else { Sign::Minus };
  162. if exponent < 0 {
  163. let one: BigInt = One::one();
  164. let denom: BigInt = one << ((-exponent) as uint);
  165. let numer: BigUint = FromPrimitive::from_u64(mantissa).unwrap();
  166. Some(Ratio::new(BigInt::from_biguint(bigint_sign, numer), denom))
  167. } else {
  168. let mut numer: BigUint = FromPrimitive::from_u64(mantissa).unwrap();
  169. numer = numer << (exponent as uint);
  170. Some(Ratio::from_integer(BigInt::from_biguint(bigint_sign, numer)))
  171. }
  172. }
  173. }
  174. /* Comparisons */
  175. // comparing a/b and c/d is the same as comparing a*d and b*c, so we
  176. // abstract that pattern. The following macro takes a trait and either
  177. // a comma-separated list of "method name -> return value" or just
  178. // "method name" (return value is bool in that case)
  179. macro_rules! cmp_impl {
  180. (impl $imp:ident, $($method:ident),+) => {
  181. cmp_impl!(impl $imp, $($method -> bool),+)
  182. };
  183. // return something other than a Ratio<T>
  184. (impl $imp:ident, $($method:ident -> $res:ty),*) => {
  185. impl<T: Mul<T,T> + $imp> $imp for Ratio<T> {
  186. $(
  187. #[inline]
  188. fn $method(&self, other: &Ratio<T>) -> $res {
  189. (self.numer * other.denom). $method (&(self.denom*other.numer))
  190. }
  191. )*
  192. }
  193. };
  194. }
  195. cmp_impl!(impl PartialEq, eq, ne)
  196. cmp_impl!(impl PartialOrd, lt -> bool, gt -> bool, le -> bool, ge -> bool,
  197. partial_cmp -> Option<cmp::Ordering>)
  198. cmp_impl!(impl Eq, )
  199. cmp_impl!(impl Ord, cmp -> cmp::Ordering)
  200. /* Arithmetic */
  201. // a/b * c/d = (a*c)/(b*d)
  202. impl<T: Clone + Integer + PartialOrd>
  203. Mul<Ratio<T>,Ratio<T>> for Ratio<T> {
  204. #[inline]
  205. fn mul(&self, rhs: &Ratio<T>) -> Ratio<T> {
  206. Ratio::new(self.numer * rhs.numer, self.denom * rhs.denom)
  207. }
  208. }
  209. // (a/b) / (c/d) = (a*d)/(b*c)
  210. impl<T: Clone + Integer + PartialOrd>
  211. Div<Ratio<T>,Ratio<T>> for Ratio<T> {
  212. #[inline]
  213. fn div(&self, rhs: &Ratio<T>) -> Ratio<T> {
  214. Ratio::new(self.numer * rhs.denom, self.denom * rhs.numer)
  215. }
  216. }
  217. // Abstracts the a/b `op` c/d = (a*d `op` b*d) / (b*d) pattern
  218. macro_rules! arith_impl {
  219. (impl $imp:ident, $method:ident) => {
  220. impl<T: Clone + Integer + PartialOrd>
  221. $imp<Ratio<T>,Ratio<T>> for Ratio<T> {
  222. #[inline]
  223. fn $method(&self, rhs: &Ratio<T>) -> Ratio<T> {
  224. Ratio::new((self.numer * rhs.denom).$method(&(self.denom * rhs.numer)),
  225. self.denom * rhs.denom)
  226. }
  227. }
  228. }
  229. }
  230. // a/b + c/d = (a*d + b*c)/(b*d)
  231. arith_impl!(impl Add, add)
  232. // a/b - c/d = (a*d - b*c)/(b*d)
  233. arith_impl!(impl Sub, sub)
  234. // a/b % c/d = (a*d % b*c)/(b*d)
  235. arith_impl!(impl Rem, rem)
  236. impl<T: Clone + Integer + PartialOrd>
  237. Neg<Ratio<T>> for Ratio<T> {
  238. #[inline]
  239. fn neg(&self) -> Ratio<T> {
  240. Ratio::new_raw(-self.numer, self.denom.clone())
  241. }
  242. }
  243. /* Constants */
  244. impl<T: Clone + Integer + PartialOrd>
  245. Zero for Ratio<T> {
  246. #[inline]
  247. fn zero() -> Ratio<T> {
  248. Ratio::new_raw(Zero::zero(), One::one())
  249. }
  250. #[inline]
  251. fn is_zero(&self) -> bool {
  252. *self == Zero::zero()
  253. }
  254. }
  255. impl<T: Clone + Integer + PartialOrd>
  256. One for Ratio<T> {
  257. #[inline]
  258. fn one() -> Ratio<T> {
  259. Ratio::new_raw(One::one(), One::one())
  260. }
  261. }
  262. impl<T: Clone + Integer + PartialOrd>
  263. Num for Ratio<T> {}
  264. impl<T: Clone + Integer + PartialOrd>
  265. Signed for Ratio<T> {
  266. #[inline]
  267. fn abs(&self) -> Ratio<T> {
  268. if self.is_negative() { -self.clone() } else { self.clone() }
  269. }
  270. #[inline]
  271. fn abs_sub(&self, other: &Ratio<T>) -> Ratio<T> {
  272. if *self <= *other { Zero::zero() } else { *self - *other }
  273. }
  274. #[inline]
  275. fn signum(&self) -> Ratio<T> {
  276. if *self > Zero::zero() {
  277. One::one()
  278. } else if self.is_zero() {
  279. Zero::zero()
  280. } else {
  281. - ::one::<Ratio<T>>()
  282. }
  283. }
  284. #[inline]
  285. fn is_positive(&self) -> bool { *self > Zero::zero() }
  286. #[inline]
  287. fn is_negative(&self) -> bool { *self < Zero::zero() }
  288. }
  289. /* String conversions */
  290. impl<T: fmt::Show + Eq + One> fmt::Show for Ratio<T> {
  291. /// Renders as `numer/denom`. If denom=1, renders as numer.
  292. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  293. if self.denom == One::one() {
  294. write!(f, "{}", self.numer)
  295. } else {
  296. write!(f, "{}/{}", self.numer, self.denom)
  297. }
  298. }
  299. }
  300. impl<T: FromStr + Clone + Integer + PartialOrd>
  301. FromStr for Ratio<T> {
  302. /// Parses `numer/denom` or just `numer`.
  303. fn from_str(s: &str) -> Option<Ratio<T>> {
  304. let mut split = s.splitn(1, '/');
  305. let num = split.next().and_then(|n| FromStr::from_str(n));
  306. let den = split.next().or(Some("1")).and_then(|d| FromStr::from_str(d));
  307. match (num, den) {
  308. (Some(n), Some(d)) => Some(Ratio::new(n, d)),
  309. _ => None
  310. }
  311. }
  312. }
  313. impl<T: FromStrRadix + Clone + Integer + PartialOrd>
  314. FromStrRadix for Ratio<T> {
  315. /// Parses `numer/denom` where the numbers are in base `radix`.
  316. fn from_str_radix(s: &str, radix: uint) -> Option<Ratio<T>> {
  317. let split: Vec<&str> = s.splitn(1, '/').collect();
  318. if split.len() < 2 {
  319. None
  320. } else {
  321. let a_option: Option<T> = FromStrRadix::from_str_radix(
  322. split[0],
  323. radix);
  324. a_option.and_then(|a| {
  325. let b_option: Option<T> =
  326. FromStrRadix::from_str_radix(split[1], radix);
  327. b_option.and_then(|b| {
  328. Some(Ratio::new(a.clone(), b.clone()))
  329. })
  330. })
  331. }
  332. }
  333. }
  334. impl<A: Clone + Integer + PartialOrd, T: Iterator<Ratio<A>>> AdditiveIterator<Ratio<A>> for T {
  335. fn sum(self) -> Ratio<A> {
  336. let init: Ratio<A> = Zero::zero();
  337. self.fold(init, |acc, x| acc + x)
  338. }
  339. }
  340. impl<A: Clone + Integer + PartialOrd, T: Iterator<Ratio<A>>> MultiplicativeIterator<Ratio<A>> for T {
  341. fn product(self) -> Ratio<A> {
  342. let init: Ratio<A> = One::one();
  343. self.fold(init, |acc, x| acc * x)
  344. }
  345. }
  346. #[cfg(test)]
  347. mod test {
  348. use super::{Ratio, Rational, BigRational};
  349. use std::num::{FromPrimitive, Float};
  350. use std::str::FromStr;
  351. use std::hash::hash;
  352. use std::i32;
  353. use {Zero, One, Signed};
  354. pub const _0 : Rational = Ratio { numer: 0, denom: 1};
  355. pub const _1 : Rational = Ratio { numer: 1, denom: 1};
  356. pub const _2: Rational = Ratio { numer: 2, denom: 1};
  357. pub const _1_2: Rational = Ratio { numer: 1, denom: 2};
  358. pub const _3_2: Rational = Ratio { numer: 3, denom: 2};
  359. pub const _NEG1_2: Rational = Ratio { numer: -1, denom: 2};
  360. pub const _1_3: Rational = Ratio { numer: 1, denom: 3};
  361. pub const _NEG1_3: Rational = Ratio { numer: -1, denom: 3};
  362. pub const _2_3: Rational = Ratio { numer: 2, denom: 3};
  363. pub const _NEG2_3: Rational = Ratio { numer: -2, denom: 3};
  364. pub fn to_big(n: Rational) -> BigRational {
  365. Ratio::new(
  366. FromPrimitive::from_int(n.numer).unwrap(),
  367. FromPrimitive::from_int(n.denom).unwrap()
  368. )
  369. }
  370. #[test]
  371. fn test_test_constants() {
  372. // check our constants are what Ratio::new etc. would make.
  373. assert_eq!(_0, Zero::zero());
  374. assert_eq!(_1, One::one());
  375. assert_eq!(_2, Ratio::from_integer(2i));
  376. assert_eq!(_1_2, Ratio::new(1i,2i));
  377. assert_eq!(_3_2, Ratio::new(3i,2i));
  378. assert_eq!(_NEG1_2, Ratio::new(-1i,2i));
  379. }
  380. #[test]
  381. fn test_new_reduce() {
  382. let one22 = Ratio::new(2i,2);
  383. assert_eq!(one22, One::one());
  384. }
  385. #[test]
  386. #[should_fail]
  387. fn test_new_zero() {
  388. let _a = Ratio::new(1i,0);
  389. }
  390. #[test]
  391. fn test_cmp() {
  392. assert!(_0 == _0 && _1 == _1);
  393. assert!(_0 != _1 && _1 != _0);
  394. assert!(_0 < _1 && !(_1 < _0));
  395. assert!(_1 > _0 && !(_0 > _1));
  396. assert!(_0 <= _0 && _1 <= _1);
  397. assert!(_0 <= _1 && !(_1 <= _0));
  398. assert!(_0 >= _0 && _1 >= _1);
  399. assert!(_1 >= _0 && !(_0 >= _1));
  400. }
  401. #[test]
  402. fn test_to_integer() {
  403. assert_eq!(_0.to_integer(), 0);
  404. assert_eq!(_1.to_integer(), 1);
  405. assert_eq!(_2.to_integer(), 2);
  406. assert_eq!(_1_2.to_integer(), 0);
  407. assert_eq!(_3_2.to_integer(), 1);
  408. assert_eq!(_NEG1_2.to_integer(), 0);
  409. }
  410. #[test]
  411. fn test_numer() {
  412. assert_eq!(_0.numer(), &0);
  413. assert_eq!(_1.numer(), &1);
  414. assert_eq!(_2.numer(), &2);
  415. assert_eq!(_1_2.numer(), &1);
  416. assert_eq!(_3_2.numer(), &3);
  417. assert_eq!(_NEG1_2.numer(), &(-1));
  418. }
  419. #[test]
  420. fn test_denom() {
  421. assert_eq!(_0.denom(), &1);
  422. assert_eq!(_1.denom(), &1);
  423. assert_eq!(_2.denom(), &1);
  424. assert_eq!(_1_2.denom(), &2);
  425. assert_eq!(_3_2.denom(), &2);
  426. assert_eq!(_NEG1_2.denom(), &2);
  427. }
  428. #[test]
  429. fn test_is_integer() {
  430. assert!(_0.is_integer());
  431. assert!(_1.is_integer());
  432. assert!(_2.is_integer());
  433. assert!(!_1_2.is_integer());
  434. assert!(!_3_2.is_integer());
  435. assert!(!_NEG1_2.is_integer());
  436. }
  437. #[test]
  438. fn test_show() {
  439. assert_eq!(format!("{}", _2), "2".to_string());
  440. assert_eq!(format!("{}", _1_2), "1/2".to_string());
  441. assert_eq!(format!("{}", _0), "0".to_string());
  442. assert_eq!(format!("{}", Ratio::from_integer(-2i)), "-2".to_string());
  443. }
  444. mod arith {
  445. use super::{_0, _1, _2, _1_2, _3_2, _NEG1_2, to_big};
  446. use super::super::{Ratio, Rational};
  447. #[test]
  448. fn test_add() {
  449. fn test(a: Rational, b: Rational, c: Rational) {
  450. assert_eq!(a + b, c);
  451. assert_eq!(to_big(a) + to_big(b), to_big(c));
  452. }
  453. test(_1, _1_2, _3_2);
  454. test(_1, _1, _2);
  455. test(_1_2, _3_2, _2);
  456. test(_1_2, _NEG1_2, _0);
  457. }
  458. #[test]
  459. fn test_sub() {
  460. fn test(a: Rational, b: Rational, c: Rational) {
  461. assert_eq!(a - b, c);
  462. assert_eq!(to_big(a) - to_big(b), to_big(c))
  463. }
  464. test(_1, _1_2, _1_2);
  465. test(_3_2, _1_2, _1);
  466. test(_1, _NEG1_2, _3_2);
  467. }
  468. #[test]
  469. fn test_mul() {
  470. fn test(a: Rational, b: Rational, c: Rational) {
  471. assert_eq!(a * b, c);
  472. assert_eq!(to_big(a) * to_big(b), to_big(c))
  473. }
  474. test(_1, _1_2, _1_2);
  475. test(_1_2, _3_2, Ratio::new(3i,4i));
  476. test(_1_2, _NEG1_2, Ratio::new(-1i, 4i));
  477. }
  478. #[test]
  479. fn test_div() {
  480. fn test(a: Rational, b: Rational, c: Rational) {
  481. assert_eq!(a / b, c);
  482. assert_eq!(to_big(a) / to_big(b), to_big(c))
  483. }
  484. test(_1, _1_2, _2);
  485. test(_3_2, _1_2, _1 + _2);
  486. test(_1, _NEG1_2, _NEG1_2 + _NEG1_2 + _NEG1_2 + _NEG1_2);
  487. }
  488. #[test]
  489. fn test_rem() {
  490. fn test(a: Rational, b: Rational, c: Rational) {
  491. assert_eq!(a % b, c);
  492. assert_eq!(to_big(a) % to_big(b), to_big(c))
  493. }
  494. test(_3_2, _1, _1_2);
  495. test(_2, _NEG1_2, _0);
  496. test(_1_2, _2, _1_2);
  497. }
  498. #[test]
  499. fn test_neg() {
  500. fn test(a: Rational, b: Rational) {
  501. assert_eq!(-a, b);
  502. assert_eq!(-to_big(a), to_big(b))
  503. }
  504. test(_0, _0);
  505. test(_1_2, _NEG1_2);
  506. test(-_1, _1);
  507. }
  508. #[test]
  509. fn test_zero() {
  510. assert_eq!(_0 + _0, _0);
  511. assert_eq!(_0 * _0, _0);
  512. assert_eq!(_0 * _1, _0);
  513. assert_eq!(_0 / _NEG1_2, _0);
  514. assert_eq!(_0 - _0, _0);
  515. }
  516. #[test]
  517. #[should_fail]
  518. fn test_div_0() {
  519. let _a = _1 / _0;
  520. }
  521. }
  522. #[test]
  523. fn test_round() {
  524. assert_eq!(_1_3.ceil(), _1);
  525. assert_eq!(_1_3.floor(), _0);
  526. assert_eq!(_1_3.round(), _0);
  527. assert_eq!(_1_3.trunc(), _0);
  528. assert_eq!(_NEG1_3.ceil(), _0);
  529. assert_eq!(_NEG1_3.floor(), -_1);
  530. assert_eq!(_NEG1_3.round(), _0);
  531. assert_eq!(_NEG1_3.trunc(), _0);
  532. assert_eq!(_2_3.ceil(), _1);
  533. assert_eq!(_2_3.floor(), _0);
  534. assert_eq!(_2_3.round(), _1);
  535. assert_eq!(_2_3.trunc(), _0);
  536. assert_eq!(_NEG2_3.ceil(), _0);
  537. assert_eq!(_NEG2_3.floor(), -_1);
  538. assert_eq!(_NEG2_3.round(), -_1);
  539. assert_eq!(_NEG2_3.trunc(), _0);
  540. assert_eq!(_1_2.ceil(), _1);
  541. assert_eq!(_1_2.floor(), _0);
  542. assert_eq!(_1_2.round(), _1);
  543. assert_eq!(_1_2.trunc(), _0);
  544. assert_eq!(_NEG1_2.ceil(), _0);
  545. assert_eq!(_NEG1_2.floor(), -_1);
  546. assert_eq!(_NEG1_2.round(), -_1);
  547. assert_eq!(_NEG1_2.trunc(), _0);
  548. assert_eq!(_1.ceil(), _1);
  549. assert_eq!(_1.floor(), _1);
  550. assert_eq!(_1.round(), _1);
  551. assert_eq!(_1.trunc(), _1);
  552. // Overflow checks
  553. let _neg1 = Ratio::from_integer(-1);
  554. let _large_rat1 = Ratio::new(i32::MAX, i32::MAX-1);
  555. let _large_rat2 = Ratio::new(i32::MAX-1, i32::MAX);
  556. let _large_rat3 = Ratio::new(i32::MIN+2, i32::MIN+1);
  557. let _large_rat4 = Ratio::new(i32::MIN+1, i32::MIN+2);
  558. let _large_rat5 = Ratio::new(i32::MIN+2, i32::MAX);
  559. let _large_rat6 = Ratio::new(i32::MAX, i32::MIN+2);
  560. let _large_rat7 = Ratio::new(1, i32::MIN+1);
  561. let _large_rat8 = Ratio::new(1, i32::MAX);
  562. assert_eq!(_large_rat1.round(), One::one());
  563. assert_eq!(_large_rat2.round(), One::one());
  564. assert_eq!(_large_rat3.round(), One::one());
  565. assert_eq!(_large_rat4.round(), One::one());
  566. assert_eq!(_large_rat5.round(), _neg1);
  567. assert_eq!(_large_rat6.round(), _neg1);
  568. assert_eq!(_large_rat7.round(), Zero::zero());
  569. assert_eq!(_large_rat8.round(), Zero::zero());
  570. }
  571. #[test]
  572. fn test_fract() {
  573. assert_eq!(_1.fract(), _0);
  574. assert_eq!(_NEG1_2.fract(), _NEG1_2);
  575. assert_eq!(_1_2.fract(), _1_2);
  576. assert_eq!(_3_2.fract(), _1_2);
  577. }
  578. #[test]
  579. fn test_recip() {
  580. assert_eq!(_1 * _1.recip(), _1);
  581. assert_eq!(_2 * _2.recip(), _1);
  582. assert_eq!(_1_2 * _1_2.recip(), _1);
  583. assert_eq!(_3_2 * _3_2.recip(), _1);
  584. assert_eq!(_NEG1_2 * _NEG1_2.recip(), _1);
  585. }
  586. #[test]
  587. fn test_to_from_str() {
  588. fn test(r: Rational, s: String) {
  589. assert_eq!(FromStr::from_str(s[]), Some(r));
  590. assert_eq!(r.to_string(), s);
  591. }
  592. test(_1, "1".to_string());
  593. test(_0, "0".to_string());
  594. test(_1_2, "1/2".to_string());
  595. test(_3_2, "3/2".to_string());
  596. test(_2, "2".to_string());
  597. test(_NEG1_2, "-1/2".to_string());
  598. }
  599. #[test]
  600. fn test_from_str_fail() {
  601. fn test(s: &str) {
  602. let rational: Option<Rational> = FromStr::from_str(s);
  603. assert_eq!(rational, None);
  604. }
  605. let xs = ["0 /1", "abc", "", "1/", "--1/2","3/2/1"];
  606. for &s in xs.iter() {
  607. test(s);
  608. }
  609. }
  610. #[test]
  611. fn test_from_float() {
  612. fn test<T: Float>(given: T, (numer, denom): (&str, &str)) {
  613. let ratio: BigRational = Ratio::from_float(given).unwrap();
  614. assert_eq!(ratio, Ratio::new(
  615. FromStr::from_str(numer).unwrap(),
  616. FromStr::from_str(denom).unwrap()));
  617. }
  618. // f32
  619. test(3.14159265359f32, ("13176795", "4194304"));
  620. test(2f32.powf(100.), ("1267650600228229401496703205376", "1"));
  621. test(-2f32.powf(100.), ("-1267650600228229401496703205376", "1"));
  622. test(1.0 / 2f32.powf(100.), ("1", "1267650600228229401496703205376"));
  623. test(684729.48391f32, ("1369459", "2"));
  624. test(-8573.5918555f32, ("-4389679", "512"));
  625. // f64
  626. test(3.14159265359f64, ("3537118876014453", "1125899906842624"));
  627. test(2f64.powf(100.), ("1267650600228229401496703205376", "1"));
  628. test(-2f64.powf(100.), ("-1267650600228229401496703205376", "1"));
  629. test(684729.48391f64, ("367611342500051", "536870912"));
  630. test(-8573.5918555f64, ("-4713381968463931", "549755813888"));
  631. test(1.0 / 2f64.powf(100.), ("1", "1267650600228229401496703205376"));
  632. }
  633. #[test]
  634. fn test_from_float_fail() {
  635. use std::{f32, f64};
  636. assert_eq!(Ratio::from_float(f32::NAN), None);
  637. assert_eq!(Ratio::from_float(f32::INFINITY), None);
  638. assert_eq!(Ratio::from_float(f32::NEG_INFINITY), None);
  639. assert_eq!(Ratio::from_float(f64::NAN), None);
  640. assert_eq!(Ratio::from_float(f64::INFINITY), None);
  641. assert_eq!(Ratio::from_float(f64::NEG_INFINITY), None);
  642. }
  643. #[test]
  644. fn test_signed() {
  645. assert_eq!(_NEG1_2.abs(), _1_2);
  646. assert_eq!(_3_2.abs_sub(&_1_2), _1);
  647. assert_eq!(_1_2.abs_sub(&_3_2), Zero::zero());
  648. assert_eq!(_1_2.signum(), One::one());
  649. assert_eq!(_NEG1_2.signum(), - ::one::<Ratio<int>>());
  650. assert!(_NEG1_2.is_negative());
  651. assert!(! _NEG1_2.is_positive());
  652. assert!(! _1_2.is_negative());
  653. }
  654. #[test]
  655. fn test_hash() {
  656. assert!(hash(&_0) != hash(&_1));
  657. assert!(hash(&_0) != hash(&_3_2));
  658. }
  659. }