I need to export expressions for numerical evaluations in a C codebase. Simplify often does a good job for this, and polynomial factorisation goes a long way.
However, occasionally I would come across things like
8 + 13 r^2 + 11 r^4 + 5 r^6 + r^8
as a subexpression. Obviously for floating point evaluation it is preferable to write this as
8 + r^2 (13 + r^2 (11 + r^2 (5 + r^2)))
Given a polynomial it is easy enough to write a function to do this conversion. The question is: how do I tell Mathematica that, after Simplify is done with its default rules, it should find all (sufficiently complicated by some metric) polynomial subexpression and turn each of them into the above "nested form"?
I wrote this question up in a hurry and perhaps didn't quite make the point clear. I'll admit I wasn't aware of
HornerForm, but that sort of really isn't the issue. As mentioned before I've quickly cooked up a bit of code to perform the same basic function already so I perhaps neglected to check if there's a built-in one.
The real issue here is that
HornerForm would undo any factorisation, that is,
Simplify may well have produced a factor of
(1 + 3 r^3 + r^7)^2
HornerForm would expand into
1 + r^3 (6 + r^3 (9 + r (2 + r^3 (6 + r^4))))
whereas I would rather prefer
(1 + 3 r^3 + r^7)^2 -> (HornerForm[1 + 3 r^3 + r^7, r])^2
(1 + r^3 (3 + r^4))^2.
HornerForm[Sqrt[1 + 3 r^3 + r^7], r]
would just fail completely, where my desired output is
Sqrt[1 + r^3 (3 + r^4)].
I suppose what I'm really looking for is to put each unfactorisable polynomial in the expression, on which
Simplify was previously applied, through
Apologies for any confusion.