Skip to content

Add Fractional, Real, and RealExt traits and update Round trait. Rename Natural trait to Integer. #6048

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Apr 25, 2013
Prev Previous commit
Update impl of Round for Ratio
  • Loading branch information
brendanzab committed Apr 25, 2013
commit 225ac216157cf530332cef1c926875e2023e48e6
42 changes: 22 additions & 20 deletions src/libstd/num/rational.rs
Original file line number Diff line number Diff line change
Expand Up @@ -204,20 +204,6 @@ impl<T: Copy + Num + Ord>
/* Utils */
impl<T: Copy + Num + Ord>
Round for Ratio<T> {
fn round(&self, mode: num::RoundMode) -> Ratio<T> {
match mode {
num::RoundUp => { self.ceil() }
num::RoundDown => { self.floor()}
num::RoundToZero => { Ratio::from_integer(self.numer / self.denom) }
num::RoundFromZero => {
if *self < Zero::zero() {
Ratio::from_integer((self.numer - self.denom + One::one()) / self.denom)
} else {
Ratio::from_integer((self.numer + self.denom - One::one()) / self.denom)
}
}
}
}

fn floor(&self) -> Ratio<T> {
if *self < Zero::zero() {
Expand All @@ -226,13 +212,29 @@ impl<T: Copy + Num + Ord>
Ratio::from_integer(self.numer / self.denom)
}
}

fn ceil(&self) -> Ratio<T> {
if *self < Zero::zero() {
Ratio::from_integer(self.numer / self.denom)
} else {
Ratio::from_integer((self.numer + self.denom - One::one()) / self.denom)
}
}

#[inline(always)]
fn round(&self) -> Ratio<T> {
if *self < Zero::zero() {
Ratio::from_integer((self.numer - self.denom + One::one()) / self.denom)
} else {
Ratio::from_integer((self.numer + self.denom - One::one()) / self.denom)
}
}

#[inline(always)]
fn trunc(&self) -> Ratio<T> {
Ratio::from_integer(self.numer / self.denom)
}

fn fract(&self) -> Ratio<T> {
Ratio::new_raw(self.numer % self.denom, self.denom)
}
Expand Down Expand Up @@ -421,18 +423,18 @@ mod test {
fn test_round() {
assert_eq!(_1_2.ceil(), _1);
assert_eq!(_1_2.floor(), _0);
assert_eq!(_1_2.round(num::RoundToZero), _0);
assert_eq!(_1_2.round(num::RoundFromZero), _1);
assert_eq!(_1_2.round(), _1);
assert_eq!(_1_2.trunc(), _0);

assert_eq!(_neg1_2.ceil(), _0);
assert_eq!(_neg1_2.floor(), -_1);
assert_eq!(_neg1_2.round(num::RoundToZero), _0);
assert_eq!(_neg1_2.round(num::RoundFromZero), -_1);
assert_eq!(_neg1_2.round(), -_1);
assert_eq!(_neg1_2.trunc(), _0);

assert_eq!(_1.ceil(), _1);
assert_eq!(_1.floor(), _1);
assert_eq!(_1.round(num::RoundToZero), _1);
assert_eq!(_1.round(num::RoundFromZero), _1);
assert_eq!(_1.round(), _1);
assert_eq!(_1.trunc(), _1);
}

#[test]
Expand Down