File tree Expand file tree Collapse file tree 1 file changed +6
-5
lines changed Expand file tree Collapse file tree 1 file changed +6
-5
lines changed Original file line number Diff line number Diff line change @@ -420,7 +420,9 @@ julia> struct OurRational{T<:Integer} <: Real
420
420
if num == 0 && den == 0
421
421
error("invalid rational: 0//0")
422
422
end
423
- g = gcd(den, num)
423
+ num = flipsign(num, den)
424
+ den = flipsign(den, den)
425
+ g = gcd(num, den)
424
426
num = div(num, g)
425
427
den = div(den, g)
426
428
new(num, den)
@@ -466,10 +468,9 @@ and `den::T` indicate that the data held in a `OurRational{T}` object are a pair
466
468
467
469
Now things get interesting. ` OurRational ` has a single inner constructor method which checks that
468
470
` num ` and ` den ` aren't both zero and ensures that every rational is constructed in "lowest
469
- terms" with a non-negative denominator. This is accomplished by dividing the given numerator and
470
- denominator values by their greatest common divisor, computed using the ` gcd ` function. Since
471
- ` gcd ` returns the greatest common divisor of its arguments with sign matching the first argument
472
- (` den ` here), after this division the new value of ` den ` is guaranteed to be non-negative. Because
471
+ terms" with a non-negative denominator. This is accomplished by first flipping the signs of numerator
472
+ and denominator if the denominator is negative. Then, both are divided by their greatest common
473
+ divisor (` gcd ` always returns a non-negative number, regardless of the sign of its arguments). Because
473
474
this is the only inner constructor for ` OurRational ` , we can be certain that ` OurRational ` objects are
474
475
always constructed in this normalized form.
475
476
You can’t perform that action at this time.
0 commit comments