Skip to content

Commit

Permalink
Remove unsafe ops for Rational (#1813)
Browse files Browse the repository at this point in the history
These are actually slower than the generic ones.
  • Loading branch information
fingolfin authored Sep 27, 2024
1 parent 2c9570b commit e5688a5
Showing 1 changed file with 0 additions and 86 deletions.
86 changes: 0 additions & 86 deletions src/julia/Rational.jl
Original file line number Diff line number Diff line change
Expand Up @@ -193,92 +193,6 @@ function log(a::Rational{T}) where T <: Integer
a != 1 && throw(DomainError(a, "a must be 1"))
end

###############################################################################
#
# Unsafe functions
#
###############################################################################

# No actual mutation is permitted for Julia types
# See #1077

function zero!(a::Rational{T}) where T <: Integer
n = a.num
n = zero!(n)
if a.den == 1
return Rational{T}(n, a.den)
else
return Rational{T}(n, T(1))
end
end

function mul!(a::Rational{T}, b::Rational{T}, c::Rational{T}) where T <: Integer
n = a.num
d = a.den
n = mul!(n, b.num, c.num)
d = mul!(d, b.den, c.den)
if d != 1 && n != 0
g = gcd(n, d)
n = divexact(n, g)
d = divexact(d, g)
end
if n == 0
return Rational{T}(n, T(1))
else
return Rational{T}(n, d)
end
end

function add!(a::Rational{T}, b::Rational{T}, c::Rational{T}) where T <: Integer
if a === b
return add!(a, c)
elseif a == c
return add!(a, b)
else # no aliasing
n = a.num
d = a.den
d = mul!(d, b.den, c.den)
n = mul!(n, b.num, c.den)
n = addmul!(n, b.den, c.num)
if d != 1 && n != 0
g = gcd(n, d)
n = divexact(n, g)
d = divexact(d, g)
end
if n == 0
return Rational{T}(n, T(1))
else
return Rational{T}(n, d)
end
end
end

function add!(a::Rational{T}, b::Rational{T}) where T <: Integer
if a === b
if iseven(a.den)
return Rational{T}(a.num, div(b.den, 2))
else
return Rational{T}(2*a.num, b.den)
end
else
n = a.num
n = mul!(n, n, b.den)
n = addmul!(n, b.num, a.den)
d = a.den
d = mul!(d, d, b.den)
if d != 1 && n != 0
g = gcd(n, d)
n = divexact(n, g)
d = divexact(d, g)
end
if n == 0
return Rational{T}(n, T(1))
else
return Rational{T}(n, d)
end
end
end

###############################################################################
#
# Random generation
Expand Down

0 comments on commit e5688a5

Please sign in to comment.