Skip to content

Commit cf313d1

Browse files
committed
Correct Ratio::is_negative and Ratio::is_positive
Zero is not positive or negative. This was broken in 8be7e7b.
1 parent 7eb666f commit cf313d1

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

src/rational.rs

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -485,11 +485,15 @@ impl<T: Clone + Integer + Signed> Signed for Ratio<T> {
485485
}
486486

487487
#[inline]
488-
fn is_positive(&self) -> bool { !self.is_negative() }
488+
fn is_positive(&self) -> bool {
489+
(self.numer.is_positive() & self.denom.is_positive()) |
490+
(self.numer.is_negative() & self.denom.is_negative())
491+
}
489492

490493
#[inline]
491494
fn is_negative(&self) -> bool {
492-
self.numer.is_negative() ^ self.denom.is_negative()
495+
(self.numer.is_negative() & self.denom.is_positive()) |
496+
(self.numer.is_positive() & self.denom.is_negative())
493497
}
494498
}
495499

@@ -603,6 +607,8 @@ mod test {
603607
pub const _1_2: Rational = Ratio { numer: 1, denom: 2};
604608
pub const _3_2: Rational = Ratio { numer: 3, denom: 2};
605609
pub const _NEG1_2: Rational = Ratio { numer: -1, denom: 2};
610+
pub const _1_NEG2: Rational = Ratio { numer: 1, denom: -2};
611+
pub const _NEG1_NEG2: Rational = Ratio { numer: -1, denom: -2};
606612
pub const _1_3: Rational = Ratio { numer: 1, denom: 3};
607613
pub const _NEG1_3: Rational = Ratio { numer: -1, denom: 3};
608614
pub const _2_3: Rational = Ratio { numer: 2, denom: 3};
@@ -1000,9 +1006,17 @@ mod test {
10001006
assert_eq!(_1_2.abs_sub(&_3_2), Zero::zero());
10011007
assert_eq!(_1_2.signum(), One::one());
10021008
assert_eq!(_NEG1_2.signum(), - ::one::<Ratio<isize>>());
1009+
assert_eq!(_0.signum(), Zero::zero());
10031010
assert!(_NEG1_2.is_negative());
1011+
assert!(_1_NEG2.is_negative());
10041012
assert!(! _NEG1_2.is_positive());
1013+
assert!(! _1_NEG2.is_positive());
1014+
assert!(_1_2.is_positive());
1015+
assert!(_NEG1_NEG2.is_positive());
10051016
assert!(! _1_2.is_negative());
1017+
assert!(! _NEG1_NEG2.is_negative());
1018+
assert!(! _0.is_positive());
1019+
assert!(! _0.is_negative());
10061020
}
10071021

10081022
#[test]

0 commit comments

Comments
 (0)