Search code examples
wolfram-mathematica

Conditional transforming an expression when encountering default value in Mathematica


Say I have an expression x + x^2 + x^3, and I want to substitute x with y when the power of x is less than its maximal power, below is my code in Mathematica:

x + x^2 + x^3 /. x^n_. /; n < 3 -> y^n

But the result is y + y^2 + y^3 instead of y + y^2 + x^3. I don't know where is my mistake.


Solution

  • You could use Replace

    Replace[x + x^2 + x^3, x^n_. /; n < 3 -> y^n, {1}]
    

    The levelspec {1} holds the replacement to level 1 where the pattern is Power[x, n] (unless n is omitted). If replacement is at level 2, the x symbols inside the Power expressions are replaced, with the n_. default coming into play. ReplaceAll (/.) affects all levels, but Replace with levelspec {1} does the job.

    Without with the n_. default an additional rule is required.

    Replace[x + x^2 + x^3, {x^n_ /; n < 3 -> y^n, x -> y}, {1}]
    

    Inverting the main rule allows use of ReplaceAll

    x + x^2 + x^3 /. {x^n_ /; n >= 3 -> x^n, x -> y}
    

    An alternative method would be to use Piecewise

    Piecewise[{{y + y^2 + x^3, n < 3}}, x + x^2 + x^3]