Skip to content

Commit cf321d0

Browse files
mbaumanvtjnashDilumAluthge
authored
Show Complex imag components directly (#53529)
Fixes #52100. This avoids doing math on the imaginary component — and instead just asks if their string representation starts with a `-` to determine whether the operator between the components should be `+` or `-`. --------- Co-authored-by: Jameson Nash <[email protected]> Co-authored-by: Dilum Aluthge <[email protected]>
1 parent 85687b5 commit cf321d0

File tree

2 files changed

+19
-8
lines changed

2 files changed

+19
-8
lines changed

base/complex.jl

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -195,16 +195,16 @@ function show(io::IO, z::Complex)
195195
r, i = reim(z)
196196
compact = get(io, :compact, false)::Bool
197197
show(io, r)
198-
if signbit(i) && !isnan(i)
198+
bufio = IOBuffer()
199+
show(IOContext(bufio, io), i)
200+
seekstart(bufio)
201+
if peek(bufio) === UInt8('-')
202+
seek(bufio, 1)
199203
print(io, compact ? "-" : " - ")
200-
if isa(i,Signed) && !isa(i,BigInt) && i == typemin(typeof(i))
201-
show(io, -widen(i))
202-
else
203-
show(io, -i)
204-
end
204+
write(io, bufio)
205205
else
206206
print(io, compact ? "+" : " + ")
207-
show(io, i)
207+
write(io, bufio)
208208
end
209209
if !(isa(i,Signed) || isa(i,AbstractFloat) && isfinite(i))
210210
print(io, "*")

test/complex.jl

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,18 @@ for T in (Int64, Float64)
2424
@test complex(Complex{T}) == Complex{T}
2525
end
2626

27+
@testset "show for complex" begin
28+
@test sprint(show, complex(1, 0), context=:compact => true) == "1+0im"
29+
@test sprint(show, complex(true, true)) == "Complex(true,true)"
30+
@test sprint(show, Complex{Int8}(0, typemin(Int8))) == "0 - 128im"
31+
32+
@test sprint(show, prevfloat(BigFloat(-1, precision=32))im) == "-0.0 - 1.0000000005im"
33+
@test sprint(show, prevfloat(BigFloat(-1, precision=512))im) == "-0.0 - 1.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000015im"
34+
35+
@test sprint(show, prevfloat(BigFloat(-1, precision=32))im, context=:compact => true) == "-0.0-1.0im"
36+
@test sprint(show, prevfloat(BigFloat(-1, precision=512))im, context=:compact => true) == "-0.0-1.0im"
37+
end
38+
2739
@testset "show" begin
2840
@test sprint(show, complex(1, 0), context=:compact => true) == "1+0im"
2941
@test sprint(show, complex(true, true)) == "Complex(true,true)"
@@ -39,7 +51,6 @@ end
3951
@test sprint(show, complex(0, -Inf)) == "0.0 - Inf*im"
4052
end
4153

42-
4354
@testset "unary operator on complex boolean" begin
4455
@test +Complex(true, true) === Complex(1, 1)
4556
@test +Complex(true, false) === Complex(1, 0)

0 commit comments

Comments
 (0)