Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixing the //(x::Number, y::Complex) one liner to accomodate silent overflows and division by zero/infinity #56478

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
30 changes: 27 additions & 3 deletions base/rational.jl
Original file line number Diff line number Diff line change
Expand Up @@ -105,9 +105,33 @@ 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)
if(iszero((x//abs2(y))) || isinf((x//abs2(y))==1//0))
return (x//abs2(y))
end
return (x//abs2(y))*conj(y)
end
function //(x::Number, y::Complex{<:Integer})
if isinf(real(y)) || isinf(imag(y))
return 0//1
end
Comment on lines +115 to +117
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If y is a complex integer isn't isinf here always false?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In issue #56245 the errors were thrown for "incorrectly assumes y is finite and nonzero" so I added conditions for for infinite and 0.

real_y = real(y)
imag_y = imag(y)
m=max(abs(real_y),abs(imag_y))
if(m==0)
return 1//0
end
scaled_a = real_y // m
scaled_b = imag_y // m
denom = (scaled_a^2 + scaled_b^2)
if iszero(denom)
return 1//0
end
real_part = (x * (((real_y//denom)//m)//m))
imag_part = (-x * (((imag_y// denom)//m)//m))
ans = (real_part + imag_part * im)
return ans
end
//(X::AbstractArray, y::Number) = X .// y

function show(io::IO, x::Rational)
Expand Down
7 changes: 6 additions & 1 deletion test/rational.jl
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,12 @@ using Test
@test -1//0 == -1//0
@test -7//0 == -1//0
@test (-1//2) // (-2//5) == 5//4

@testset "Complex//Number Overflow" begin
for y ∈ (1 // 0, -1 // 0)
@test (7 // complex(y)) == (7 // y)
end
@test Int8(8) // Int8(100)im == 0//1 - 2//25*im
end
@test_throws OverflowError -(0x01//0x0f)
@test_throws OverflowError -(typemin(Int)//1)
@test_throws OverflowError (typemax(Int)//3) + 1
Expand Down