Skip to content

Commit

Permalink
fix: limitDenominator crashing
Browse files Browse the repository at this point in the history
  • Loading branch information
abdel-17 committed Jan 15, 2024
1 parent 7904324 commit 82a56dc
Showing 1 changed file with 13 additions and 2 deletions.
15 changes: 13 additions & 2 deletions Sources/RationalModule/Rational.swift
Original file line number Diff line number Diff line change
Expand Up @@ -166,15 +166,15 @@ extension Rational {
var d = denominator

while true {
let a = n / d
let a = floorDivision(n, d)
let q2 = q0 + a * q1
guard q2 <= max else { break }

(p0, q0, p1, q1) = (p1, q1, p0 + a * p1, q2)
(n, d) = (d, n - a * d)
}

let k = (max - q0) / q1
let k = floorDivision((max - q0), q1)
return if 2 * d * (q0 + k * q1) <= denominator {
Self(numerator: p1, denominator: q1)
} else {
Expand All @@ -183,6 +183,17 @@ extension Rational {
}
}

/// Equivalent to Python's `//` operator.
@usableFromInline
internal func floorDivision<T: BinaryInteger>(_ a: T, _ b: T) -> T {
let quotient = a / b
return if a >= 0 {
quotient
} else {
quotient - 1
}
}

// MARK: - Rounding
extension Rational {
/// The greatest integer less than or equal to this value.
Expand Down

0 comments on commit 82a56dc

Please sign in to comment.