How to define verbose output (for a polynomial)?

Let’s say I have a polynomial given by p_k(x) = x^k + \sum_{i=0}^{k-1} c_i x^i. Clearly, the coefficients c_i fully characterize my polynomial. So specifying

julia> c = [-1., 2., 3.] # = [c_0, c_1, c_2]


suffices to evaluate p_3(x) = x^3 + 3x^2 + 2x - 1. What I want is a function show(c::Vector{Float}) that outputs the polynomial as a nicely formatted string:

julia> show(c)
x^3 + 3x^2 + 2x - 1


What would be a clean way to approach this? I’ve started to write something down but it’s messy (loads of string concatenations)…

thanks heaps!

struct Poly
coeffs
end
function Base.show(io::IO, p::Poly)
coeffs = p.coeffs
print(io, "x^", length(coeffs))
for (i, c) in enumerate(reverse(coeffs))
c == 0 && continue

ex = length(coeffs) - i
print(io, ' ', c > 0 ? '+' : '-', ' ')
print(io, abs(c))
ex > 0 && print(io, 'x')
ex > 1 && print(io, '^', ex)
end
end

julia> Poly([1,-2,-3])
x^3 - 3x^2 - 2x + 1

julia> Poly([0])
x^1

julia> Poly([0, 2, 0, 3])
x^4 + 3x^3 + 2x

julia> Poly(rand(10).-0.5)
x^10 + 0.2606507488640739x^9 - 0.06205419788927036x^8 - 0.41674910676955257x^7 - 0.47426298505535147x^6 - 0.45989301750947376x^5 - 0.44154324205320594x^4 + 0.30222167946906886x^3 - 0.15677329726552958x^2 - 0.08422882092642103x - 0.11469693082642762


Cool! This looks nice!

Chopping off some decimals of abs(c) would improve the output even more, I guess.

function Base.show(io::IO, p::Poly)
coeffs = p.coeffs
print(io, "x^", length(coeffs))
for (i, c) in enumerate(reverse(coeffs))
c == 0 && continue

ex = length(coeffs) - i
print(io, ' ', c > 0 ? '+' : '-', ' ')
print(io, abs(round(c, sigdigits=2)))
ex > 0 && print(io, 'x')
ex > 1 && print(io, '^', ex)
end
end

julia> Poly(rand(10).-0.5)
x^10 - 0.5x^9 - 0.47x^8 - 0.41x^7 + 0.16x^6 - 0.3x^5 - 0.14x^4 + 0.17x^3 + 0.25x^2 - 0.0077x + 0.19

julia> Poly(rand(10).^rand(10).-0.5)
x^10 - 0.17x^9 + 0.47x^8 + 0.49x^7 - 0.057x^6 - 0.17x^5 + 0.44x^4 + 0.27x^3 - 0.25x^2 + 0.041x - 0.09

julia> Poly(rand(10).-0.5)
x^10 + 0.2x^9 - 0.36x^8 + 0.0081x^7 + 0.12x^6 - 0.31x^5 + 0.37x^4 + 0.43x^3 - 0.093x^2 - 0.37x - 0.29

julia> Poly([1,-2,-3.165])
x^3 - 3.2x^2 - 2.0x + 1.0

2 Likes

sweet! thanks so much.

today I learned: print(io, ..)