Skip to content

Commit bf05fd1

Browse files
authored
doc: fix OurRational example for current gcd behavior (#39935)
1 parent 135d7a0 commit bf05fd1

File tree

1 file changed

+6
-5
lines changed

1 file changed

+6
-5
lines changed

doc/src/manual/constructors.md

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -420,7 +420,9 @@ julia> struct OurRational{T<:Integer} <: Real
420420
if num == 0 && den == 0
421421
error("invalid rational: 0//0")
422422
end
423-
g = gcd(den, num)
423+
num = flipsign(num, den)
424+
den = flipsign(den, den)
425+
g = gcd(num, den)
424426
num = div(num, g)
425427
den = div(den, g)
426428
new(num, den)
@@ -466,10 +468,9 @@ and `den::T` indicate that the data held in a `OurRational{T}` object are a pair
466468

467469
Now things get interesting. `OurRational` has a single inner constructor method which checks that
468470
`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
473474
this is the only inner constructor for `OurRational`, we can be certain that `OurRational` objects are
474475
always constructed in this normalized form.
475476

0 commit comments

Comments
 (0)