Skip to content

Commit

Permalink
Add round(::Type{Complex{T}}, Complex{S})
Browse files Browse the repository at this point in the history
This is useful for doing things like `round.(Complex{Int16}, complex_data)`,
when you need to coerce to a single datatype.
  • Loading branch information
staticfloat committed Oct 11, 2022
1 parent a68235c commit 40d1af3
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
5 changes: 5 additions & 0 deletions base/complex.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1100,6 +1100,11 @@ function round(z::Complex, rr::RoundingMode=RoundNearest, ri::RoundingMode=rr; k
round(imag(z), ri; kwargs...))
end

function round(::Type{T}, z::Complex{T}) where {T}
Complex{T}(round(T, real(z)),
round(T, imag(z)))
end


float(z::Complex{<:AbstractFloat}) = z
float(z::Complex) = Complex(float(real(z)), float(imag(z)))
Expand Down
11 changes: 11 additions & 0 deletions test/complex.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1209,3 +1209,14 @@ end
@test !iseven(7+0im) && isodd(7+0im)
@test !iseven(6+1im) && !isodd(7+1im)
end

@testset "Complex{T} -> Complex{S} rounding" begin
z = Complex{Float64}(2^15 + 0.6, 2^15 - 0.6)
z_i32 = round(Complex{Int32}, z)
@test isa(z_i32, Complex{Int32})
@test isa(real(z_i32),Int32)
@test real(z_i32) == 2^15 + 1
@test imag(z_i32) == 2^15 - 1

@test_throws InexactError round(Complex{Int16}, z)
end

0 comments on commit 40d1af3

Please sign in to comment.