How can I determine the coefficients of a polynom?
using Symbolics
@variables R a b c d U J Q s
input = 2s + 4U*a*s^2 + Q*(J+s)
function split_s(input::Num)
end
res = split_s(input)
# expected output:
# the factors of s², of s and without s
# [4U*a, 2+Q, Q*J]
function split_s(input)
inp = simplify(input, expand=true)
vcat([Num(Symbolics.coeff(inp, s^i)) for i in Symbolics.degree(inp, s):-1:1],
substitute(inp, s => 0))
end
You are right, this was done quite hastily. I’ll remove it from the answer. TBH not really an expert on Symbolics.jl, just fiddled around. Oops… my code doesn’t actually have this. Was confused by reply to me. Tagging @ufechner7
It seems like someone has already thought of this feature.
The biggest difficulty is understanding that the second argument must be a tuple.
julia> polynomial_coeffs(input, s)
ERROR: MethodError: no method matching iterate(::SymbolicUtils.BasicSymbolic{Real})
julia> polynomial_coeffs(input, (s,))
(Dict{Any, Any}(s^2 => 4U*a, s => 2 + Q, 1 => J*Q), 0)
help?> polynomial_coeffs
search: polynomial_coeffs
polynomial_coeffs(expr, vars)
Find coefficients of a polynomial in vars.
Returns a tuple of two elements:
1. A dictionary of coefficients keyed by
monomials in vars
2. A residual expression which is the
constant term