Skip to content

Commit

Permalink
define numerator and denominator for Complex (#55694)
Browse files Browse the repository at this point in the history
Fixes #55693
  • Loading branch information
nsajko authored Sep 12, 2024
1 parent 4079648 commit e52a46c
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
11 changes: 9 additions & 2 deletions base/rational.jl
Original file line number Diff line number Diff line change
Expand Up @@ -293,8 +293,14 @@ julia> numerator(4)
4
```
"""
numerator(x::Integer) = x
numerator(x::Union{Integer,Complex{<:Integer}}) = x
numerator(x::Rational) = x.num
function numerator(z::Complex{<:Rational})
den = denominator(z)
reim = (real(z), imag(z))
result = checked_mul.(numerator.(reim), div.(den, denominator.(reim)))
complex(result...)
end

"""
denominator(x)
Expand All @@ -310,8 +316,9 @@ julia> denominator(4)
1
```
"""
denominator(x::Integer) = one(x)
denominator(x::Union{Integer,Complex{<:Integer}}) = one(x)
denominator(x::Rational) = x.den
denominator(z::Complex{<:Rational}) = lcm(denominator(real(z)), denominator(imag(z)))

sign(x::Rational) = oftype(x, sign(x.num))
signbit(x::Rational) = signbit(x.num)
Expand Down
17 changes: 17 additions & 0 deletions test/rational.jl
Original file line number Diff line number Diff line change
Expand Up @@ -801,3 +801,20 @@ end
@test rationalize(Int64, nextfloat(0.1) * im; tol=0) == precise_next * im
@test rationalize(0.1im; tol=eps(0.1)) == rationalize(0.1im)
end

@testset "complex numerator, denominator" begin
z = complex(3*3, 2*3*5)
@test z === numerator(z) === numerator(z // 2) === numerator(z // 5)
@test complex(3, 2*5) === numerator(z // 3)
@test isone(denominator(z))
@test 2 === denominator(z // 2)
@test 1 === denominator(z // 3)
@test 5 === denominator(z // 5)
for den 1:10
q = z // den
@test q === (numerator(q)//denominator(q))
end
@testset "do not overflow silently" begin
@test_throws OverflowError numerator(Int8(1)//Int8(31) + Int8(8)im//Int8(3))
end
end

0 comments on commit e52a46c

Please sign in to comment.