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.
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.
17 use std::from_str::FromStr;
18 use std::num::{Zero, One, ToStrRadix, FromStrRadix};
19 use bigint::{BigInt, BigUint, Sign, Plus, Minus};
21 /// Represents the ratio between 2 numbers.
29 /// Alias for a `Ratio` of machine-sized integers.
30 pub type Rational = Ratio<int>;
31 pub type Rational32 = Ratio<i32>;
32 pub type Rational64 = Ratio<i64>;
34 /// Alias for arbitrary precision rationals.
35 pub type BigRational = Ratio<BigInt>;
37 impl<T: Clone + Integer + PartialOrd>
39 /// Create a ratio representing the integer `t`.
41 pub fn from_integer(t: T) -> Ratio<T> {
42 Ratio::new_raw(t, One::one())
45 /// Create a ratio without checking for `denom == 0` or reducing.
47 pub fn new_raw(numer: T, denom: T) -> Ratio<T> {
48 Ratio { numer: numer, denom: denom }
51 /// Create a new Ratio. Fails if `denom == 0`.
53 pub fn new(numer: T, denom: T) -> Ratio<T> {
54 if denom == Zero::zero() {
55 fail!("denominator == 0");
57 let mut ret = Ratio::new_raw(numer, denom);
62 /// Convert to an integer.
64 pub fn to_integer(&self) -> T {
68 /// Gets an immutable reference to the numerator.
70 pub fn numer<'a>(&'a self) -> &'a T {
74 /// Gets an immutable reference to the denominator.
76 pub fn denom<'a>(&'a self) -> &'a T {
80 /// Return true if the rational number is an integer (denominator is 1).
82 pub fn is_integer(&self) -> bool {
83 self.denom == One::one()
86 /// Put self into lowest terms, with denom > 0.
87 fn reduce(&mut self) {
88 let g : T = self.numer.gcd(&self.denom);
90 // FIXME(#5992): assignment operator overloads
92 self.numer = self.numer / g;
93 // FIXME(#5992): assignment operator overloads
95 self.denom = self.denom / g;
97 // keep denom positive!
98 if self.denom < Zero::zero() {
99 self.numer = -self.numer;
100 self.denom = -self.denom;
104 /// Return a `reduce`d copy of self.
105 pub fn reduced(&self) -> Ratio<T> {
106 let mut ret = self.clone();
111 /// Return the reciprocal
113 pub fn recip(&self) -> Ratio<T> {
114 Ratio::new_raw(self.denom.clone(), self.numer.clone())
117 pub fn floor(&self) -> Ratio<T> {
118 if *self < Zero::zero() {
119 Ratio::from_integer((self.numer - self.denom + One::one()) / self.denom)
121 Ratio::from_integer(self.numer / self.denom)
125 pub fn ceil(&self) -> Ratio<T> {
126 if *self < Zero::zero() {
127 Ratio::from_integer(self.numer / self.denom)
129 Ratio::from_integer((self.numer + self.denom - One::one()) / self.denom)
134 pub fn round(&self) -> Ratio<T> {
135 if *self < Zero::zero() {
136 Ratio::from_integer((self.numer - self.denom + One::one()) / self.denom)
138 Ratio::from_integer((self.numer + self.denom - One::one()) / self.denom)
143 pub fn trunc(&self) -> Ratio<T> {
144 Ratio::from_integer(self.numer / self.denom)
147 pub fn fract(&self) -> Ratio<T> {
148 Ratio::new_raw(self.numer % self.denom, self.denom.clone())
153 /// Converts a float into a rational number
154 pub fn from_float<T: Float>(f: T) -> Option<BigRational> {
158 let (mantissa, exponent, sign) = f.integer_decode();
159 let bigint_sign: Sign = if sign == 1 { Plus } else { Minus };
161 let one: BigInt = One::one();
162 let denom: BigInt = one << ((-exponent) as uint);
163 let numer: BigUint = FromPrimitive::from_u64(mantissa).unwrap();
164 Some(Ratio::new(BigInt::from_biguint(bigint_sign, numer), denom))
166 let mut numer: BigUint = FromPrimitive::from_u64(mantissa).unwrap();
167 numer = numer << (exponent as uint);
168 Some(Ratio::from_integer(BigInt::from_biguint(bigint_sign, numer)))
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),+)
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> {
188 fn $method(&self, other: &Ratio<T>) -> $res {
189 (self.numer * other.denom). $method (&(self.denom*other.numer))
195 cmp_impl!(impl PartialEq, eq, ne)
196 cmp_impl!(impl PartialOrd, lt, gt, le, ge)
198 cmp_impl!(impl Ord, cmp -> cmp::Ordering)
201 // a/b * c/d = (a*c)/(b*d)
202 impl<T: Clone + Integer + PartialOrd>
203 Mul<Ratio<T>,Ratio<T>> for Ratio<T> {
205 fn mul(&self, rhs: &Ratio<T>) -> Ratio<T> {
206 Ratio::new(self.numer * rhs.numer, self.denom * rhs.denom)
210 // (a/b) / (c/d) = (a*d)/(b*c)
211 impl<T: Clone + Integer + PartialOrd>
212 Div<Ratio<T>,Ratio<T>> for Ratio<T> {
214 fn div(&self, rhs: &Ratio<T>) -> Ratio<T> {
215 Ratio::new(self.numer * rhs.denom, self.denom * rhs.numer)
219 // Abstracts the a/b `op` c/d = (a*d `op` b*d) / (b*d) pattern
220 macro_rules! arith_impl {
221 (impl $imp:ident, $method:ident) => {
222 impl<T: Clone + Integer + PartialOrd>
223 $imp<Ratio<T>,Ratio<T>> for Ratio<T> {
225 fn $method(&self, rhs: &Ratio<T>) -> Ratio<T> {
226 Ratio::new((self.numer * rhs.denom).$method(&(self.denom * rhs.numer)),
227 self.denom * rhs.denom)
233 // a/b + c/d = (a*d + b*c)/(b*d
234 arith_impl!(impl Add, add)
236 // a/b - c/d = (a*d - b*c)/(b*d)
237 arith_impl!(impl Sub, sub)
239 // a/b % c/d = (a*d % b*c)/(b*d)
240 arith_impl!(impl Rem, rem)
242 impl<T: Clone + Integer + PartialOrd>
243 Neg<Ratio<T>> for Ratio<T> {
245 fn neg(&self) -> Ratio<T> {
246 Ratio::new_raw(-self.numer, self.denom.clone())
251 impl<T: Clone + Integer + PartialOrd>
254 fn zero() -> Ratio<T> {
255 Ratio::new_raw(Zero::zero(), One::one())
259 fn is_zero(&self) -> bool {
260 *self == Zero::zero()
264 impl<T: Clone + Integer + PartialOrd>
267 fn one() -> Ratio<T> {
268 Ratio::new_raw(One::one(), One::one())
272 impl<T: Clone + Integer + PartialOrd>
275 /* String conversions */
276 impl<T: fmt::Show> fmt::Show for Ratio<T> {
277 /// Renders as `numer/denom`.
278 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
279 write!(f, "{}/{}", self.numer, self.denom)
282 impl<T: ToStrRadix> ToStrRadix for Ratio<T> {
283 /// Renders as `numer/denom` where the numbers are in base `radix`.
284 fn to_str_radix(&self, radix: uint) -> String {
286 self.numer.to_str_radix(radix),
287 self.denom.to_str_radix(radix))
291 impl<T: FromStr + Clone + Integer + PartialOrd>
292 FromStr for Ratio<T> {
293 /// Parses `numer/denom`.
294 fn from_str(s: &str) -> Option<Ratio<T>> {
295 let split: Vec<&str> = s.splitn('/', 1).collect();
299 let a_option: Option<T> = FromStr::from_str(*split.get(0));
300 a_option.and_then(|a| {
301 let b_option: Option<T> = FromStr::from_str(*split.get(1));
302 b_option.and_then(|b| {
303 Some(Ratio::new(a.clone(), b.clone()))
308 impl<T: FromStrRadix + Clone + Integer + PartialOrd>
309 FromStrRadix for Ratio<T> {
310 /// Parses `numer/denom` where the numbers are in base `radix`.
311 fn from_str_radix(s: &str, radix: uint) -> Option<Ratio<T>> {
312 let split: Vec<&str> = s.splitn('/', 1).collect();
316 let a_option: Option<T> = FromStrRadix::from_str_radix(
319 a_option.and_then(|a| {
320 let b_option: Option<T> =
321 FromStrRadix::from_str_radix(*split.get(1), radix);
322 b_option.and_then(|b| {
323 Some(Ratio::new(a.clone(), b.clone()))
333 use super::{Ratio, Rational, BigRational};
334 use std::num::{Zero, One, FromStrRadix, FromPrimitive, ToStrRadix};
335 use std::from_str::FromStr;
337 pub static _0 : Rational = Ratio { numer: 0, denom: 1};
338 pub static _1 : Rational = Ratio { numer: 1, denom: 1};
339 pub static _2: Rational = Ratio { numer: 2, denom: 1};
340 pub static _1_2: Rational = Ratio { numer: 1, denom: 2};
341 pub static _3_2: Rational = Ratio { numer: 3, denom: 2};
342 pub static _neg1_2: Rational = Ratio { numer: -1, denom: 2};
344 pub fn to_big(n: Rational) -> BigRational {
346 FromPrimitive::from_int(n.numer).unwrap(),
347 FromPrimitive::from_int(n.denom).unwrap()
352 fn test_test_constants() {
353 // check our constants are what Ratio::new etc. would make.
354 assert_eq!(_0, Zero::zero());
355 assert_eq!(_1, One::one());
356 assert_eq!(_2, Ratio::from_integer(2i));
357 assert_eq!(_1_2, Ratio::new(1i,2i));
358 assert_eq!(_3_2, Ratio::new(3i,2i));
359 assert_eq!(_neg1_2, Ratio::new(-1i,2i));
363 fn test_new_reduce() {
364 let one22 = Ratio::new(2i,2);
366 assert_eq!(one22, One::one());
371 let _a = Ratio::new(1i,0);
377 assert!(_0 == _0 && _1 == _1);
378 assert!(_0 != _1 && _1 != _0);
379 assert!(_0 < _1 && !(_1 < _0));
380 assert!(_1 > _0 && !(_0 > _1));
382 assert!(_0 <= _0 && _1 <= _1);
383 assert!(_0 <= _1 && !(_1 <= _0));
385 assert!(_0 >= _0 && _1 >= _1);
386 assert!(_1 >= _0 && !(_0 >= _1));
391 fn test_to_integer() {
392 assert_eq!(_0.to_integer(), 0);
393 assert_eq!(_1.to_integer(), 1);
394 assert_eq!(_2.to_integer(), 2);
395 assert_eq!(_1_2.to_integer(), 0);
396 assert_eq!(_3_2.to_integer(), 1);
397 assert_eq!(_neg1_2.to_integer(), 0);
403 assert_eq!(_0.numer(), &0);
404 assert_eq!(_1.numer(), &1);
405 assert_eq!(_2.numer(), &2);
406 assert_eq!(_1_2.numer(), &1);
407 assert_eq!(_3_2.numer(), &3);
408 assert_eq!(_neg1_2.numer(), &(-1));
412 assert_eq!(_0.denom(), &1);
413 assert_eq!(_1.denom(), &1);
414 assert_eq!(_2.denom(), &1);
415 assert_eq!(_1_2.denom(), &2);
416 assert_eq!(_3_2.denom(), &2);
417 assert_eq!(_neg1_2.denom(), &2);
422 fn test_is_integer() {
423 assert!(_0.is_integer());
424 assert!(_1.is_integer());
425 assert!(_2.is_integer());
426 assert!(!_1_2.is_integer());
427 assert!(!_3_2.is_integer());
428 assert!(!_neg1_2.is_integer());
433 use super::{_0, _1, _2, _1_2, _3_2, _neg1_2, to_big};
434 use super::super::{Ratio, Rational};
438 fn test(a: Rational, b: Rational, c: Rational) {
439 assert_eq!(a + b, c);
440 assert_eq!(to_big(a) + to_big(b), to_big(c));
443 test(_1, _1_2, _3_2);
445 test(_1_2, _3_2, _2);
446 test(_1_2, _neg1_2, _0);
451 fn test(a: Rational, b: Rational, c: Rational) {
452 assert_eq!(a - b, c);
453 assert_eq!(to_big(a) - to_big(b), to_big(c))
456 test(_1, _1_2, _1_2);
457 test(_3_2, _1_2, _1);
458 test(_1, _neg1_2, _3_2);
463 fn test(a: Rational, b: Rational, c: Rational) {
464 assert_eq!(a * b, c);
465 assert_eq!(to_big(a) * to_big(b), to_big(c))
468 test(_1, _1_2, _1_2);
469 test(_1_2, _3_2, Ratio::new(3i,4i));
470 test(_1_2, _neg1_2, Ratio::new(-1i, 4i));
475 fn test(a: Rational, b: Rational, c: Rational) {
476 assert_eq!(a / b, c);
477 assert_eq!(to_big(a) / to_big(b), to_big(c))
481 test(_3_2, _1_2, _1 + _2);
482 test(_1, _neg1_2, _neg1_2 + _neg1_2 + _neg1_2 + _neg1_2);
487 fn test(a: Rational, b: Rational, c: Rational) {
488 assert_eq!(a % b, c);
489 assert_eq!(to_big(a) % to_big(b), to_big(c))
492 test(_3_2, _1, _1_2);
493 test(_2, _neg1_2, _0);
494 test(_1_2, _2, _1_2);
499 fn test(a: Rational, b: Rational) {
501 assert_eq!(-to_big(a), to_big(b))
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);
525 assert_eq!(_1_2.ceil(), _1);
526 assert_eq!(_1_2.floor(), _0);
527 assert_eq!(_1_2.round(), _1);
528 assert_eq!(_1_2.trunc(), _0);
530 assert_eq!(_neg1_2.ceil(), _0);
531 assert_eq!(_neg1_2.floor(), -_1);
532 assert_eq!(_neg1_2.round(), -_1);
533 assert_eq!(_neg1_2.trunc(), _0);
535 assert_eq!(_1.ceil(), _1);
536 assert_eq!(_1.floor(), _1);
537 assert_eq!(_1.round(), _1);
538 assert_eq!(_1.trunc(), _1);
543 assert_eq!(_1.fract(), _0);
544 assert_eq!(_neg1_2.fract(), _neg1_2);
545 assert_eq!(_1_2.fract(), _1_2);
546 assert_eq!(_3_2.fract(), _1_2);
551 assert_eq!(_1 * _1.recip(), _1);
552 assert_eq!(_2 * _2.recip(), _1);
553 assert_eq!(_1_2 * _1_2.recip(), _1);
554 assert_eq!(_3_2 * _3_2.recip(), _1);
555 assert_eq!(_neg1_2 * _neg1_2.recip(), _1);
559 fn test_to_from_str() {
560 fn test(r: Rational, s: String) {
561 assert_eq!(FromStr::from_str(s.as_slice()), Some(r));
562 assert_eq!(r.to_str(), s);
564 test(_1, "1/1".to_string());
565 test(_0, "0/1".to_string());
566 test(_1_2, "1/2".to_string());
567 test(_3_2, "3/2".to_string());
568 test(_2, "2/1".to_string());
569 test(_neg1_2, "-1/2".to_string());
572 fn test_from_str_fail() {
574 let rational: Option<Rational> = FromStr::from_str(s);
575 assert_eq!(rational, None);
578 let xs = ["0 /1", "abc", "", "1/", "--1/2","3/2/1"];
579 for &s in xs.iter() {
585 fn test_to_from_str_radix() {
586 fn test(r: Rational, s: String, n: uint) {
587 assert_eq!(FromStrRadix::from_str_radix(s.as_slice(), n),
589 assert_eq!(r.to_str_radix(n).to_string(), s);
591 fn test3(r: Rational, s: String) { test(r, s, 3) }
592 fn test16(r: Rational, s: String) { test(r, s, 16) }
594 test3(_1, "1/1".to_string());
595 test3(_0, "0/1".to_string());
596 test3(_1_2, "1/2".to_string());
597 test3(_3_2, "10/2".to_string());
598 test3(_2, "2/1".to_string());
599 test3(_neg1_2, "-1/2".to_string());
600 test3(_neg1_2 / _2, "-1/11".to_string());
602 test16(_1, "1/1".to_string());
603 test16(_0, "0/1".to_string());
604 test16(_1_2, "1/2".to_string());
605 test16(_3_2, "3/2".to_string());
606 test16(_2, "2/1".to_string());
607 test16(_neg1_2, "-1/2".to_string());
608 test16(_neg1_2 / _2, "-1/4".to_string());
609 test16(Ratio::new(13i,15i), "d/f".to_string());
610 test16(_1_2*_1_2*_1_2*_1_2, "1/10".to_string());
614 fn test_from_str_radix_fail() {
616 let radix: Option<Rational> = FromStrRadix::from_str_radix(s, 3);
617 assert_eq!(radix, None);
620 let xs = ["0 /1", "abc", "", "1/", "--1/2","3/2/1", "3/2"];
621 for &s in xs.iter() {
627 fn test_from_float() {
628 fn test<T: Float>(given: T, (numer, denom): (&str, &str)) {
629 let ratio: BigRational = Ratio::from_float(given).unwrap();
630 assert_eq!(ratio, Ratio::new(
631 FromStr::from_str(numer).unwrap(),
632 FromStr::from_str(denom).unwrap()));
636 test(3.14159265359f32, ("13176795", "4194304"));
637 test(2f32.powf(100.), ("1267650600228229401496703205376", "1"));
638 test(-2f32.powf(100.), ("-1267650600228229401496703205376", "1"));
639 test(1.0 / 2f32.powf(100.), ("1", "1267650600228229401496703205376"));
640 test(684729.48391f32, ("1369459", "2"));
641 test(-8573.5918555f32, ("-4389679", "512"));
644 test(3.14159265359f64, ("3537118876014453", "1125899906842624"));
645 test(2f64.powf(100.), ("1267650600228229401496703205376", "1"));
646 test(-2f64.powf(100.), ("-1267650600228229401496703205376", "1"));
647 test(684729.48391f64, ("367611342500051", "536870912"));
648 test(-8573.5918555f64, ("-4713381968463931", "549755813888"));
649 test(1.0 / 2f64.powf(100.), ("1", "1267650600228229401496703205376"));
653 fn test_from_float_fail() {
656 assert_eq!(Ratio::from_float(f32::NAN), None);
657 assert_eq!(Ratio::from_float(f32::INFINITY), None);
658 assert_eq!(Ratio::from_float(f32::NEG_INFINITY), None);
659 assert_eq!(Ratio::from_float(f64::NAN), None);
660 assert_eq!(Ratio::from_float(f64::INFINITY), None);
661 assert_eq!(Ratio::from_float(f64::NEG_INFINITY), None);