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)…
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
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