Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 26 additions & 2 deletions base/rational.jl
Original file line number Diff line number Diff line change
Expand Up @@ -105,8 +105,32 @@ function //(x::Rational, y::Rational)
end

//(x::Complex, y::Real) = complex(real(x)//y, imag(x)//y)
//(x::Number, y::Complex) = x*conj(y)//abs2(y)

function //(x::Number, y::Complex{<:Rational})
c, d = reim(y)
if (isinf(c) | isinf(d))
x * conj(zero(y))
else
x * conj(y)
end//abs2(y)
end
function //(x::Number, y::Complex{<:Integer})
c, d = reim(y)
c_r, d_r = divgcd(c, d)
abs2y_r = checked_add(checked_mul(c, c_r), checked_mul(d, d_r))
(x * complex(c_r, checked_neg(d_r)))//abs2y_r
end
function //(x::Integer, y::Complex{<:Integer})
complex(x) // y
end
function //(x::Complex{<:Integer}, y::Complex{<:Integer})
a, b, c, d = promote(reim(x)..., reim(y)...)
c_r, d_r = divgcd(c, d)
abs2y_r = checked_add(checked_mul(c, c_r), checked_mul(d, d_r))
complex(
checked_add(checked_mul(a, c_r), checked_mul(b, d_r)),
checked_add(checked_mul(b, c_r), checked_neg(checked_mul(a, d_r)))
)//abs2y_r
end

//(X::AbstractArray, y::Number) = X .// y

Expand Down
20 changes: 20 additions & 0 deletions test/rational.jl
Original file line number Diff line number Diff line change
Expand Up @@ -215,9 +215,17 @@ end
@test_throws DivideError (0//1) / complex(0, 0)
@test_throws DivideError (1//1) / complex(0, 0)
@test_throws DivideError (1//0) / complex(0, 0)
@test_throws DivideError complex(1//0) // complex(1//0, 1//0)
@test_throws DivideError 1 // complex(0, 0)
@test_throws DivideError 0 // complex(0, 0)
@test_throws DivideError complex(1) // complex(0, 0)
@test_throws DivideError complex(0) // complex(0, 0)

# 1//200 - 1//200*im cannot be represented as Complex{Rational{Int8}}
@test_throws OverflowError (Int8(1)//Int8(1)) / (Int8(100) + Int8(100)im)
@test_throws OverflowError (Int8(1)//Int8(1)) // (Int8(100) + Int8(100)im)
@test_throws OverflowError Int8(1) // (Int8(100) + Int8(100)im)
@test_throws OverflowError complex(Int8(1)) // (Int8(100) + Int8(100)im)

@test Complex(rand_int, 0) == Rational(rand_int)
@test Rational(rand_int) == Complex(rand_int, 0)
Expand All @@ -243,6 +251,14 @@ end
end
end
end
@testset "exact division by an infinite complex number" begin
for y ∈ (1 // 0, -1 // 0)
@test (7 // complex(y)) == 0
@test (Rational(7) // complex(y)) == 0
@test (complex(7) // complex(y)) == 0
@test (complex(Rational(7)) // complex(y)) == 0
end
end
end

# check type of constructed rationals
Expand Down Expand Up @@ -626,6 +642,10 @@ end
# issue #16282
@test_throws MethodError 3 // 4.5im

# issue #60137
@test_throws MethodError 3.0 // (1 + 0im)
@test_throws MethodError 3.0 // (1//0 + 0im)

# issue #31396
@test round(1//2, RoundNearestTiesUp) === 1//1

Expand Down