Skip to content

Commit edbd29b

Browse files
committed
Fixed some bugs in the printing implementation. Added support for # - # instead of # + -#. Broke into two methods - complex and real
1 parent 54b55bf commit edbd29b

File tree

1 file changed

+55
-25
lines changed

1 file changed

+55
-25
lines changed

src/Polynomial.jl

Lines changed: 55 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -54,38 +54,68 @@ function show(io::IO, p::Poly)
5454
print(io,p)
5555
print(io,")")
5656
end
57-
function print{T}(io::IO, p::Poly{T})
58-
parens = !(T<:Real)
57+
58+
function print{T<:Real}(io::IO, p::Poly{T})
5959
n = length(p)
6060
if n <= 0
6161
print(io,"0")
6262
else
63-
for i = 1:n
64-
pi = p[i]
65-
if abs(pi) > 2*eps(T)
66-
i > 1 && print(io," + ")
67-
if i == n || abs(pi-1) > 2*eps(T)
68-
if T <: Complex
69-
if real(pi) > 2*eps(T)
70-
if imag(pi) > 2*eps(T)
71-
print(io,'(',pi,')')
72-
else
73-
print(io,real(pi))
74-
end
75-
else
76-
if imag(pi) > 2*eps(T)
77-
print(io,'(',imag(pi),"im)")
78-
else
79-
print(io,'0')
80-
end
81-
end
63+
for j = 1:n
64+
pj = p[j]
65+
magpj = abs(pj)
66+
if magpj > 2*eps(T)
67+
if j == 1
68+
pj < 0 && print(io, "-") #Prepend - if first and negative
69+
else
70+
pj < 0 ? print(io," - ") : print(" + ")
71+
end
72+
#Print pj if pj is the last coefficient, or pj is not identically 1
73+
if j == n || abs(magpj - 1) > 2*eps(T)
74+
print(io, magpj)
75+
end
76+
exp = n-j
77+
if exp > 0
78+
print(io, p.var)
79+
if exp > 1
80+
print(io, '^', exp)
81+
end
82+
end
83+
end
84+
end
85+
end
86+
end
87+
88+
function print{T<:ComplexPair}(io::IO, p::Poly{T})
89+
n = length(p)
90+
if n <= 0
91+
print(io,"0")
92+
else
93+
for j = 1:n
94+
pj = p[j]
95+
abs_repj = abs(real(pj))
96+
abs_impj = abs(imag(pj))
97+
if abs(pj) > 2*eps(T)
98+
if !(abs_impj > 2*eps(T))
99+
if j > 1
100+
real(pj) < 0 ? print(io," - ") : print(" + ")
82101
else
83-
parens && print(io,'(')
84-
print(io, pi)
85-
parens && print(io,')')
102+
real(pj) < 0 && print(io, "-") #Prepend - if first and negative
103+
end
104+
else
105+
j > 1 && print(io, " + ")
106+
end
107+
if abs_repj > 2*eps(T) #Real part is not 0
108+
if abs_impj > 2*eps(T) #Imag part is not 0
109+
print(io,'(',pj,')')
110+
elseif abs(abs_repj - 1) > 2*eps(T) || j == n
111+
print(io,abs_repj)
112+
end
113+
else
114+
if abs_impj > 2*eps(T)
115+
print(io,'(', imag(pj),"im)")
86116
end
87117
end
88-
exp = n-i
118+
exp = n-j
89119
if exp > 0
90120
print(io, p.var)
91121
if exp > 1

0 commit comments

Comments
 (0)