I wrote the following function to calculate the sum of a vector of rational numbers:
function rationalsum(numbers::Vector{T} where T<:Rational)
den = lcm([x.den for x in numbers])
nums = (x.num * div(den, x.den) for x in numbers)
return sum(nums)//den
end
In my benchmarks it is 4-8 times faster than sum() (depending on the rational numbers). My first assumption was that this is because the sum() method looks for the common denominator at every step. But the performance ratio between the two appears to be close to constant, so this is likely not the explanation. Is my implementation bad or missing something?