Ratios.RatiosModule

Ratios provides SimpleRatio, a faster variant of Rational. Speed comes at the cost of greater vulnerability to overflow.

API summary:

  • r = SimpleRatio(num, den) is equivalent to num // den
  • common_denominator standardizes a collection of SimpleRatios to have the same denominator, making some arithmetic operations among them less likely to overflow.
Ratios.SimpleRatioMethod
SimpleRatio(num::Integer, den::Integer)

Construct the equivalent of the rational number num // den.

Operations with SimpleRatio are faster, but also more vulnerable to integer overflow, than with Rational. Arithmetic with SimpleRatio does not perform any simplification of the resulting ratios. The best defense against overflow is to use ratios with the same denominator: in such cases, + and - will skip forming the product of denominators. See common_denominator.

If overflow is a risk, consider constructing them using SaferIntegers.jl.

Examples

julia> x, y, z = SimpleRatio(1, 8), SimpleRatio(1, 4), SimpleRatio(2, 8)
(SimpleRatio{Int64}(1, 8), SimpleRatio{Int64}(1, 4), SimpleRatio{Int64}(2, 8))

julia> x+y
SimpleRatio{Int64}(12, 32)

julia> x+z
SimpleRatio{Int64}(3, 8)
Ratios.common_denominatorMethod
common_denominator(x::SimpleRatio, ys::SimpleRatio...)

Return the equivalent of (x, ys...) but using a common denominator. This can be useful to avoid overflow.

Info

This function is quite slow. In performance-sensitive contexts where the ratios are constructed with literal constants, it is better to ensure a common denominator at the time of original construction.