Skip to content

Commit e1aa30c

Browse files
committed
Even smarter printing of complex coefficients
1 parent fea9996 commit e1aa30c

File tree

3 files changed

+85
-73
lines changed

3 files changed

+85
-73
lines changed

src/show.jl

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,15 @@ function printproductsign(io::IO, pj::T, j, mimetype) where {T}
159159
(showone(T) || pj != one(T)) && print(io, showop(mimetype, "*"))
160160
end
161161

162+
function printproductsign(io::IO, pj::T, j, mimetype) where {T<:Complex}
163+
j == 0 && return
164+
(a,b) = reim(pj)
165+
!iszero(a) && !iszero(b) && return # parentheses inserted, no * needed
166+
!iszero(a) && return printproductsign(io, a, j, mimetype)
167+
print(io, showop(mimetype, "*"))
168+
end
169+
170+
162171
# show a single term
163172
# Other types can overload Polynomials.printcofficient with a mimetype
164173
# or Base.show_unquoted(io, pj, indent, prec)
@@ -210,7 +219,7 @@ function printcoefficient(io::IO, pj::S, j, mimetype) where {T,S <: Complex{T}}
210219
hasimag = !iszero(b) || isnan(b) || isinf(b)
211220

212221
if hasreal && hasimag
213-
print(io, "(")
222+
iszero(j) || print(io, "(")
214223
print(io, a)
215224

216225
# print b
@@ -232,7 +241,7 @@ function printcoefficient(io::IO, pj::S, j, mimetype) where {T,S <: Complex{T}}
232241
end
233242

234243
print(io, imagsymbol(mimetype))
235-
print(io, ")")
244+
iszero(j) || print(io, ")")
236245

237246
elseif hasreal
238247

test/Poly.jl

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -286,15 +286,16 @@ p = Poly([1.0, 2.0, 3.0, 1.0])
286286
p = Poly([1, im])
287287
@test repr(p) == "Poly(1 + im*x)"
288288
p = Poly([1+im, 1-im, -1+im, -1 - im])# minus signs
289-
@test repr(p) == "Poly((1 + 1im) + (1 - 1im)*x - (1 - 1im)*x^2 - (1 + 1im)*x^3)"
289+
@test repr(p) == "Poly(1 + im + (1 - im)x - (1 - im)x^2 - (1 + im)x^3)"
290290
p = Poly([1.0, 0 + NaN*im, NaN, Inf, 0 - Inf*im]) # handle NaN or Inf appropriately
291291
@test repr(p) == "Poly(1.0 + NaN*im*x + NaN*x^2 + Inf*x^3 - Inf*im*x^4)"
292292

293293
p = Poly([1,2,3])
294-
295294
@test repr("text/latex", p) == "\$1 + 2\\cdot x + 3\\cdot x^{2}\$"
296295
p = Poly([1//2, 2//3, 1])
297296
@test repr("text/latex", p) == "\$\\frac{1}{2} + \\frac{2}{3}\\cdot x + x^{2}\$"
297+
p = Poly([complex(1,1),complex(0,1),complex(1,0),complex(1,1)])
298+
@test repr("text/latex", p) == "\$1 + i + i\\cdot x + x^{2} + (1 + i)x^{3}\$"
298299

299300
# customized printing with printpoly
300301
function printpoly_to_string(args...; kwargs...)

0 commit comments

Comments
 (0)