Skip to content

Commit 16a47f6

Browse files
authored
Merge pull request #23 from dmytro-sheyko/master
Fixes #22: Comparison when one of the denominators is negative and both numbers are positive
2 parents 4c833e3 + ec8ef55 commit 16a47f6

File tree

2 files changed

+24
-6
lines changed

2 files changed

+24
-6
lines changed

src/Rationals/Comparisons.cs

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -66,12 +66,9 @@ public int CompareTo(Rational other)
6666
{
6767
if (Sign == other.Sign)
6868
{
69-
if (Sign >= 0)
70-
return (Numerator * other.Denominator).CompareTo(other.Numerator * Denominator);
71-
72-
return
73-
-BigInteger.Abs(Numerator * other.Denominator)
74-
.CompareTo(BigInteger.Abs(other.Numerator * Denominator));
69+
BigInteger adjDenominator = BigInteger.Abs(Denominator) * other.Denominator.Sign;
70+
BigInteger adjOtherDenominator = BigInteger.Abs(other.Denominator) * Denominator.Sign;
71+
return (Numerator * adjOtherDenominator).CompareTo(other.Numerator * adjDenominator);
7572
}
7673

7774
if (Sign > other.Sign)

tests/Rationals.Tests/ComparisonsTests.cs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,27 @@ public void Comparisons2()
6060
Assert.True(b <= a);
6161
}
6262

63+
[Fact]
64+
public void ComparisonsNegativeDenominator()
65+
{
66+
// arrange
67+
var a = new Rational(3);
68+
var b = new Rational(-4, -1);
69+
70+
// assert
71+
Assert.Equal(-1, a.CompareTo(b));
72+
Assert.False(a > b);
73+
Assert.False(a >= b);
74+
Assert.True(a < b);
75+
Assert.True(a <= b);
76+
77+
Assert.Equal(+1, b.CompareTo(a));
78+
Assert.True(b > a);
79+
Assert.True(b >= a);
80+
Assert.False(b < a);
81+
Assert.False(b <= a);
82+
}
83+
6384
[Fact]
6485
public void Equality1()
6586
{

0 commit comments

Comments
 (0)