Skip to content

Fix issue #15826. #16778

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 1 commit into from
Aug 31, 2014
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 29 additions & 6 deletions src/libnum/rational.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,15 +137,14 @@ impl<T: Clone + Integer + PartialOrd>
}

/// Rounds to the nearest integer. Rounds half-way cases away from zero.
///
/// Note: This function is currently broken and always rounds away from zero.
#[inline]
pub fn round(&self) -> Ratio<T> {
// FIXME(#15826)
if *self < Zero::zero() {
Ratio::from_integer((self.numer - self.denom + One::one()) / self.denom)
// a/b - 1/2 = (2*a - b)/(2*b)
Ratio::from_integer((self.numer + self.numer - self.denom) / (self.denom + self.denom))
} else {
Ratio::from_integer((self.numer + self.denom - One::one()) / self.denom)
// a/b + 1/2 = (2*a + b)/(2*b)
Ratio::from_integer((self.numer + self.numer + self.denom) / (self.denom + self.denom))
}
}

Expand Down Expand Up @@ -388,7 +387,11 @@ mod test {
pub static _2: Rational = Ratio { numer: 2, denom: 1};
pub static _1_2: Rational = Ratio { numer: 1, denom: 2};
pub static _3_2: Rational = Ratio { numer: 3, denom: 2};
pub static _neg1_2: Rational = Ratio { numer: -1, denom: 2};
pub static _neg1_2: Rational = Ratio { numer: -1, denom: 2};
pub static _1_3: Rational = Ratio { numer: 1, denom: 3};
pub static _neg1_3: Rational = Ratio { numer: -1, denom: 3};
pub static _2_3: Rational = Ratio { numer: 2, denom: 3};
pub static _neg2_3: Rational = Ratio { numer: -2, denom: 3};

pub fn to_big(n: Rational) -> BigRational {
Ratio::new(
Expand Down Expand Up @@ -578,6 +581,26 @@ mod test {

#[test]
fn test_round() {
assert_eq!(_1_3.ceil(), _1);
assert_eq!(_1_3.floor(), _0);
assert_eq!(_1_3.round(), _0);
assert_eq!(_1_3.trunc(), _0);

assert_eq!(_neg1_3.ceil(), _0);
assert_eq!(_neg1_3.floor(), -_1);
assert_eq!(_neg1_3.round(), _0);
assert_eq!(_neg1_3.trunc(), _0);

assert_eq!(_2_3.ceil(), _1);
assert_eq!(_2_3.floor(), _0);
assert_eq!(_2_3.round(), _1);
assert_eq!(_2_3.trunc(), _0);

assert_eq!(_neg2_3.ceil(), _0);
assert_eq!(_neg2_3.floor(), -_1);
assert_eq!(_neg2_3.round(), -_1);
assert_eq!(_neg2_3.trunc(), _0);

assert_eq!(_1_2.ceil(), _1);
assert_eq!(_1_2.floor(), _0);
assert_eq!(_1_2.round(), _1);
Expand Down