3

If I do something like

1/Sqrt[x] /. {Sqrt[x] -> a}

it does not lead to an expected result, but can be fixed with

1/Sqrt[x] /. {Sqrt[x] -> a, 1/Sqrt[x] -> 1/a}

I am wondering if, for given g[x] and h[x], there exists a general way of replacing any f[g[x]] with f[h[x]]?

mavzolej
  • 693
  • 4
  • 10
  • 2
    You have to see FullForm of your expression to write a working replacement rule. – Daniel Huber Apr 11 '22 at 20:30
  • Sometimes results are better replacing a single variable rather than an expression. 1/Sqrt[x] /. {x -> a^2} // PowerExpand. – Bill Watts Apr 11 '22 at 20:45
  • Possible duplicate: https://mathematica.stackexchange.com/a/29219/4999 -- the question at the end seems to have no relation to the implicit question in the beginning examples. – Michael E2 Apr 12 '22 at 03:54

2 Answers2

5
{Sqrt[x], 1/Sqrt[x]} // FullForm

List[Power[x,Rational[1,2]],Power[x,Rational[-1,2]]]

Try:

rule = Power[x, Rational[g_, 2]] -> a^Sign[g]
{Sqrt[x], 1/Sqrt[x]} /. rule

{a, 1/a}


For your other query:

f[g[x]] /. g -> h

f[h[x]]

Syed
  • 52,495
  • 4
  • 30
  • 85
  • Thank you. Note that, strictly speaking, my second question is the generalization of the first one, yet I cannot do smth like Sqrt -> ... (say, for replacing Sqrt[x] with some constant a) – mavzolej Apr 11 '22 at 20:38
  • 2
    Sqrt gets translated as above using Fullform. Replacements work mechanically and don't interpret user's intention so a literal rule is needed. – Syed Apr 11 '22 at 20:39
2

Extended comment

1/Sqrt[x] // FullForm

ff

The following works

expr = 1/Sqrt[x];
Numerator[expr]/(Denominator[expr] /. Sqrt[x] -> a)

1/a

The general replacement an be done as follows:

fun = f[g[x]] + D[f[g[x]], x]
fun /. g -> Function[{x}, a^2 h[x]]

1 2

bmf
  • 15,157
  • 2
  • 26
  • 63