JuliaMath / Polynomials.jl

Polynomial manipulations in Julia
http://juliamath.github.io/Polynomials.jl/
Other
303 stars 75 forks source link

Get coefficient from Symbolics.jl's expression? #437

Closed phpsmarter closed 2 years ago

phpsmarter commented 2 years ago

I want to write more algebraic style code , so do this

here is the code for eigen polynomials with pluto note

  1. get algebraic expression with symbolcs.jl
 using  Symbolics, LinearAlgebra, RowEchelon, Latexify , Polynomials
 @variables A,λ,I, poly
  A=[-5 2;-7 4]
  I= diagm([1,1])
  poly=det(A-λ*I)
  res=expand(poly)
  latexify(res~0)

so , I can get eigen polynomial of matrices.

  1. find eigen value
     poly=Polynomial([-6,1,1],:λ)
     roots=roots(poly)

could get coefficients from symbolics expression directly?

jverzani commented 2 years ago

I think you want to bypass Polynomials, right? If so, I found this thread to be helpful:

julia> d = Symbolics.value(res).dict
Dict{Any, Number} with 2 entries:
  λ^2 => 1
  λ   => 1

To get the constant, something akin to this would be needed:

julia> substitute(res, Dict(λ=>0))
-6

This set of commands could be used to get a Polynomial object:

julia> dd = Dict(Symbolics.degree(first(kv)) => kv[2] for kv ∈ d)
Dict{Int64, Int64} with 2 entries:
  2 => 1
  1 => 1

julia> dd[0] = substitute(res, Dict(λ=>0)).val
-6

julia> SparsePolynomial(dd, :λ)
SparsePolynomial(-6 + λ + λ^2)

That thread is a year old, perhaps there is another solution out there.

phpsmarter commented 2 years ago

I think you want to bypass Polynomials, right? If so, I found this thread to be helpful:

Thanks. This is exactly what I want

get eigen value of matrix by symbolics algebra

let
 @variables A,λ,I,x,poly
  A=[3 0 2; 6 4 3; -4 0 -3]
  I=diagm([1,1,1])  
  poly=(A-λ*I)|>det|>expand     # characteristic polynomial of matrix
  coffes_dict = Symbolics.value(poly).dict
  dd = Dict(Symbolics.degree(first(kv)) => kv[2] for kv ∈ coffes_dict)
  dd[0] = substitute(poly, Dict(λ=>0)).val
  characteristicpoly= SparsePolynomial(dd, :λ)
  roots=roots(characteristicpoly)
end 
jverzani commented 2 years ago

Hi, I'm closing this. Re-open if I read the conclusion wrong.