Skip to content

Commit 40d1af3

Browse files
committed
Add round(::Type{Complex{T}}, Complex{S})
This is useful for doing things like `round.(Complex{Int16}, complex_data)`, when you need to coerce to a single datatype.
1 parent a68235c commit 40d1af3

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

base/complex.jl

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1100,6 +1100,11 @@ function round(z::Complex, rr::RoundingMode=RoundNearest, ri::RoundingMode=rr; k
11001100
round(imag(z), ri; kwargs...))
11011101
end
11021102

1103+
function round(::Type{T}, z::Complex{T}) where {T}
1104+
Complex{T}(round(T, real(z)),
1105+
round(T, imag(z)))
1106+
end
1107+
11031108

11041109
float(z::Complex{<:AbstractFloat}) = z
11051110
float(z::Complex) = Complex(float(real(z)), float(imag(z)))

test/complex.jl

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1209,3 +1209,14 @@ end
12091209
@test !iseven(7+0im) && isodd(7+0im)
12101210
@test !iseven(6+1im) && !isodd(7+1im)
12111211
end
1212+
1213+
@testset "Complex{T} -> Complex{S} rounding" begin
1214+
z = Complex{Float64}(2^15 + 0.6, 2^15 - 0.6)
1215+
z_i32 = round(Complex{Int32}, z)
1216+
@test isa(z_i32, Complex{Int32})
1217+
@test isa(real(z_i32),Int32)
1218+
@test real(z_i32) == 2^15 + 1
1219+
@test imag(z_i32) == 2^15 - 1
1220+
1221+
@test_throws InexactError round(Complex{Int16}, z)
1222+
end

0 commit comments

Comments
 (0)