Skip to content

Commit fea9996

Browse files
committed
Smarter showing of complex numbers
1 parent 6605bc5 commit fea9996

File tree

1 file changed

+42
-12
lines changed

1 file changed

+42
-12
lines changed

src/show.jl

Lines changed: 42 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -203,24 +203,51 @@ function printcoefficient(io::IO, a::Rational{T}, j, mimetype::MIME"text/latex")
203203
end
204204

205205
# print complex numbers with parentheses as needed
206-
function printcoefficient(io::IO, pj::Complex{T}, j, mimetype) where {T}
206+
function printcoefficient(io::IO, pj::S, j, mimetype) where {T,S <: Complex{T}}
207207

208-
hasreal = abs(real(pj)) > 0 || isnan(real(pj)) || isinf(real(pj))
209-
hasimag = abs(imag(pj)) > 0 || isnan(imag(pj)) || isinf(imag(pj))
208+
(a,b) = reim(pj)
209+
hasreal = !iszero(a) || isnan(a) || isinf(a)
210+
hasimag = !iszero(b) || isnan(b) || isinf(b)
210211

211212
if hasreal && hasimag
212-
Base.show_unquoted(io, pj, 0, Base.operator_precedence(:*))
213+
print(io, "(")
214+
print(io, a)
215+
216+
# print b
217+
if isone(b) || isone(-b)
218+
if hasneg(S) && b < 0
219+
print(io, showop(mimetype, "-"))
220+
else
221+
print(io, showop(mimetype, "+"))
222+
end
223+
else
224+
if hasneg(S) && b < 0
225+
print(io, showop(mimetype, "-"))
226+
(showone(S) || !isone(-b)) && print(io, -b)
227+
else
228+
print(io, showop(mimetype,"+"))
229+
print(io, b)
230+
end
231+
(isnan(b) || isinf(b)) && print(io, showop(mimetype, "*"))
232+
end
233+
234+
print(io, imagsymbol(mimetype))
235+
print(io, ")")
236+
213237
elseif hasreal
214-
a = real(pj)
215-
(j==0 || showone(T) || a != one(T)) && printcoefficient(io, a, j, mimetype)
238+
239+
(iszero(j) || showone(T) || isone(a)) && printcoefficient(io, a, j, mimetype)
240+
216241
elseif hasimag
217-
b = imag(pj)
218-
(showone(T) || b != one(T)) && printcoefficient(io, b, j, mimetype)
219-
(isnan(imag(pj)) || isinf(imag(pj))) && print(io, showop(mimetype, "*"))
220-
print(io, im)
221-
else
222-
return nothing
242+
243+
(showone(T) || !isone(b)) && printcoefficient(io, b, j, mimetype)
244+
(isnan(b) || isinf(b)) && print(io, showop(mimetype, "*"))
245+
print(io, imagsymbol(mimetype))
246+
223247
end
248+
249+
return nothing
250+
224251
end
225252

226253
## show exponent
@@ -252,3 +279,6 @@ function unicode_subscript(io, j)
252279
print(io, a[Int(i)-44])
253280
end
254281
end
282+
283+
imagsymbol(::Any) = "im"
284+
imagsymbol(::MIME"text/latex") = "i"

0 commit comments

Comments
 (0)