Re: Replacement problem
- To: mathgroup at smc.vnet.net
- Subject: [mg36911] Re: [mg36906] Replacement problem
- From: Andrzej Kozlowski <andrzej at platon.c.u-tokyo.ac.jp>
- Date: Wed, 2 Oct 2002 03:31:33 -0400 (EDT)
- Sender: owner-wri-mathgroup at wolfram.com
Hm, I wonder whose "failures" are you referring to when write "substitution failures in 4.2"? When using Mathematica's pattern matching there is one fundamental rule (very frequently restated on this list) you should adhere to: check the FullForm of the expression you are trying to match. So taking just your first case: In[1]:= FullForm[f = B*(A + Sqrt[X + Y + Z]) + C/((Sqrt[X + Y + Z]/4)*F^2)] Out[2]//FullForm= Plus[Times[4,C,Power[ F,-2],Power[Plus[X,Y,Z],Rational[-1,2]]],Times[B,Plus[A,Power[Plus[X, Y,Z],Rational[1,2]]]]] This ought to make the reason for the failure of your substitution clear. To make it work you must find a way to much the right pattern and not forget that the matching is purely syntactic. In[2]:= f /. (X + Y + Z)^(Rational[x_, 2]) -> Q^x Out[2]= (4*C)/(F^2*Q) + B*(A + Q) There are of course other ways you can get this to work, e.g. In[3]:= PowerExpand[f /. X + Y + Z -> Q^2] Out[3]= (4*C)/(F^2*Q) + B*(A + Q) There is even a rather crazy method that sometimes actually works: In[4]:= ToExpression[StringReplace[ToString[Evaluate[InputForm[f]]], "Sqrt[X + Y + Z]" -> "Q"]] Out[4]= (4*C)/(F^2*Q) + B*(A + Q) Andrzej Kozlowski Toyama International University JAPAN http://sigma.tuins.ac.jp/~andrzej/ On Tuesday, October 1, 2002, at 05:46 PM, Carlos Felippa wrote: > These expressions are condensation of larger ones > (about 700 lines or so each) but they illustrate random > substitution failures in 4.2. Question: how can the > substitution Sqrt[...]->Q always be made to work? > The help file under ReplaceAll, ReplaceRepeated, etc, > does not address this problem. > > Thanks > > > f=B*(A+Sqrt[X+Y+Z])+C/(Sqrt[X+Y+Z]/4*F^2); > Print[(f/.Sqrt[X+Y+Z]->Q)//InputForm]; > > B*(A + Q) + (4*C)/(F^2*Sqrt[X + Y + Z]) (* fails *) > > g=B*(A+Sqrt[X+Y+Z])+C/(Sqrt[X+Y+Z]*4*F^2); > Print[(g/.Sqrt[X+Y+Z]->Q)//InputForm]; > > B*(A + Q) + C/(4*F^2*Sqrt[X + Y + Z]) (* fails *) > > h=B*(A+Sqrt[X+Y+Z])+C/(Sqrt[X+Y+Z]+4*F^2); > Print[(h/.Sqrt[X+Y+Z]->Q)//InputForm]; > > B*(A + Q) + C/(4*F^2 + Q) (* works *) > > >