0
$\begingroup$

I would like to redefine a function f(x)=1+2x^2 to a new function g(y)=1+2y by using the replacement x^2 -> y. However, in the MWE below, only Method 1 gives me the correct one.

What's wrong with the other two methods? Can they be repaired? I am asking because it may not always be possible to write the replacement in terms of x (e.g. say, 3x^2-4x+2 -> y).

    f[x_] := 1 + 2 x^2;

    g[y_] = f[y /. y -> Sqrt[y]];
    Print["Method 1: g(y)=", g[y]];

    g[y_] := Replace[f[y], y^2 -> y];
    Print["Method 2: g(y)=", g[y]];

    g[y_] = f[y /. y^2 -> y];
    Print["Method 3: g(y)=", g[y]];
$\endgroup$
1
$\begingroup$

For Replace you must include the levels at which to map the replacement. By default it does not map to subparts.

g[y_] := Replace[f[y], y^2 -> y, Infinity];
Print["Method 2: g(y)=", g[y]];

For /. {Replace All} your syntax is incorrect.

g[y_] := f[y] /. y^2 -> y;
Print["Method 3: g(y)=", g[y]];
$\endgroup$
  • $\begingroup$ Thanks. Now if I modify the replacement a bit, e.g. 1-2x^2->y , then I expect 1+2x^2=2-(1-2x^2)=2-y. However, g[y_] := f[y] /. 1 - 2 y^2 -> y; gives me 1+2y^2! Am I missing something again? $\endgroup$ – hbaromega Dec 18 '14 at 17:44
0
$\begingroup$

Replace and ReplaceAll functions perform only structural replacements, they don't know that some expressions may be mathematically equivalent.

To perform full change of variables you can solve equation relating one variable to another and then perform substitution using obtained solutions.

In case from question:

ClearAll[xToY];
xToY = Solve[\[FormalY] == 1 - 2 \[FormalX]^2, \[FormalX]]
(* {
    {\[FormalX] -> -(Sqrt[1 - \[FormalY]]/Sqrt[2])},
    {\[FormalX] -> Sqrt[1 - \[FormalY]]/Sqrt[2]}
} *)

now that we have x in terms of y we can perform substitution in our function:

ClearAll[g];
g[\[FormalY]_] = f[\[FormalX]] /. xToY[[1]] // FullSimplify;

Note that I used Set (=) instead of SetDelayed (:=), so that RHS of g definition is evaluated and replacement and simplifications are done only once when defining g and not each time g is called. To make sure that RHS can be safely evaluated, without accidentally using some predefined value of x or y, I used formal symbols.

Now g is defined as:

??g
(* Global`g
g[\[FormalY]_]=2-\[FormalY] *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.