Symbolics substitute and simplify in a polynomial

This is my first time using Symbolics.

I have a polynomial that I want to substitute a variable and then simplify the result as shown.

julia> dcs_P1 = 229.50752 - 321.64369 * r - 121.01008 * r^2 + 53.15226 * r^3
229.50752 + 53.15226(r^3) - 121.01008(r^2) - 321.64369r

julia> dcs_P1ₙ = simplify.(substitute.(dcs_P1, (Dict(r => rₙ - 0.0475),)))
(244.785595275 + 53.15226((rₙ - 0.0475)^3) - 121.01008((rₙ - 0.0475)^2) - 321.64369rₙ,)

The simplification works for the linear part, but not the squared or cubic part. If I use Horner’s method, it does not help.

julia> dcs_P1 = 229.50752 - r*(321.64369 - r*(121.01008 + r*53.15226))
229.50752 - r*(321.64369 - r*(121.01008 + 53.15226r))

julia> dcs_P1ₙ = simplify.(substitute.(dcs_P1, (Dict(r => rₙ - 0.0475),)))
(229.50752 - (rₙ - 0.0475)*(321.64369 - (rₙ - 0.0475)*(118.48534765000001 + 53.15226rₙ)),)

Is there something I am missing or is this functionality yet to be developed?

I have MathCad 14 which uses Maple for its Symbolic engine and it solves the problem.

What exactly is the desired output? I guess “simplifying” is not uniquely defined. If you want to have a polynomial in rₙ in the “usual” form, simplify has a few keyword arguments.

Docstring
help?> simplify
search: simplify simplify_fractions

  simplify(x; expand=false,
              threaded=false,
              thread_subtree_cutoff=100,
              rewriter=nothing)

  Simplify an expression (x) by applying rewriter until there are no changes. expand=true applies expand (/api/#expand) in the beginning
  of each fixpoint iteration.

  By default, simplify will assume denominators are not zero and allow cancellation in fractions. Pass simplify_fractions=false to
  prevent this.

By using expand=true in your example, we can get the (I assume) desired output

julia> dcs_P1ₙ = simplify.(substitute.(dcs_P1, (Dict(r => rₙ - 0.0475),)); expand=true)
(244.5068698546353 + 53.15226(rₙ^3) - 309.787958040125rₙ - 128.58427705(rₙ^2),)
1 Like

Your assumptions were correct, good reminder to look at the docstring as well as the tutorial. I can cut and paste to put the result into a function.

1 Like

Happy I could help :slight_smile:

Absolutely, it took me a while to realize and get used to just hitting ? and search the built-in docs. As a bonus, it really makes one appreciate the effort many package authors put into their docstrings.

Ah, one more think I just remembered: There is also a tutorial specifically about defining your own “rewriters” – you can put them as a kwarg into simplify. If you have a very specific final form of the symbolic expression in mind, it might be useful to define such custom simplification rules:

https://symbolicutils.juliasymbolics.org/rewrite/