Consider this given example for ReplaceAll
1 + x^2 + x^4 /. x^p_ -> f[p]
This returns 1+f[2]+f[4]
- works good (!). But if you choose
In[175]:= 1 +x+ x^2 + x^4 /. x^p_ -> f[p]
Out[175]= 1+x+f[2]+f[4]
It doesn't not work for 1
and x
. The correct output should be f[0]+f[1]+f[2]+f[4]
.
What is wrong here and to cure it?
EDIT
Possible way out
One possible way out can be to not use ReplaceAll
(inspired by @eldo). The coefficient and the power of x
can be combined in this way:
fun[x] = a - b x + c x^2 + d x^4
nfun = Exponent[fun[x], x];
Sum[Coefficient[fun[x], x, i] f[i], {i, 0, nfun}]
And the result is a f[0] - b f[1] + c f[2] + d f[4]
.
However the replace rule for $x^0$ is still a mystery!
Answer
It would be cumbersome with ReplaceAll
. I suggest to use Exponent
instead:
Plus @@ (f /@ Exponent[1 + x + x^2 + x^4, x, List])
f[0] + f[1] + f[2] + f[4]
Considering Öska's objection
Alternating signs are not easily handled, maybe something like this:
fun1 = 1 - x - x^2 + x^4;
fun2 = List @@ fun1;
minus = Position[fun2, Times[-1, __]] // Flatten;
plus = Complement[Range@Length@fun2, minus];
fun3 = (f /@ Exponent[fun1, x, List]);
Plus @@ Join[Part[fun3, plus], Part[fun3, minus] /. a_ :> -a]
f[0] - f[1] - f[2] + f[4]
ADDENDUM
This can be shortened to:
Plus @@ (D[#, x] & /@ MonomialList@fun1 /. Times[a_?NumberQ, __] :> a /.
a_?NumberQ :> f[Abs@a]*Sign@a /. (0) -> f@0*First@fun1)
f[0] - f[1] - f[2] + f[4]
Comments
Post a Comment