1
$\begingroup$

Let's consider the following example

Rd0 = Sqrt[R^2 + (a + Sqrt[h^2 + z^2])^2];
Rn0 = Sqrt[R^2 + z^2] - rs;

Vd = -Md/Rd0;
Vn = -Mn/Rn0;

Veff = Vd + Vn + Lz^2/(2*R^2);

VR = D[Veff, R];

The expression VR gives

-(Lz^2/R^3)+(Mn R)/(Sqrt[R^2+z^2] (-rs+Sqrt[R^2+z^2])^2)+(Md R)/
 (R^2+(a+Sqrt[h^2+z^2])^2)^(3/2)

Now I want to replace some expressions, using the rule

rule = {Sqrt[h^2 + z^2] -> Rdz; Sqrt[R^2 + z^2] -> Rcn; 
          (R^2 + (a + Sqrt[h^2 + z^2])^2)^(3/2) -> Rd^3};

However, when I apply it as VR /. rule1 I get

-(Lz^2/R^3)+(Mn R)/((Rcn-rs)^2 Sqrt[R^2+z^2])+(Md R)/
 (R^2+(a+Sqrt[h^2+z^2])^2)^(3/2)

As we see, only one of the terms has been replaced, while all the others have not been replaced. So my question is: how can I efficiently replay all the expressions according to the above rule?

$\endgroup$
2
  • $\begingroup$ It seems to me that the semicolon in 'rule' in the first entry is a typo: the second expression you seem to want is lost. Changing it to a comma already makes your expression simpler $\endgroup$
    – JJBK
    Commented Nov 11, 2019 at 10:57
  • $\begingroup$ @JJBK I corrected the typo but the problem remains. $\endgroup$
    – Vaggelis_Z
    Commented Nov 11, 2019 at 10:59

1 Answer 1

2
$\begingroup$

As often with replacements in mathematical expressions, the problem is that the FullForm of an expression is not what we might think it is. In this case, consider the second term of VR:

VR[[2]]//FullForm
(* Times[
    Mn,
    R,
    Power[Plus[Power[R,2],Power[z,2]],Rational[-1,2]],
    Power[Plus[Times[-1,rs],Power[Plus[Power[R,2],Power[z,2]],Rational[1,2]]],-2]
   ] *)

Notice the Power[…,Rational[-1,2]] expression for the $1/\sqrt{\cdots}$ part. This means you need to adapt the pattern to handle both 1/2 and -1/2 as exponent. The easiest way to do this here is:

rule = {
   Sqrt[h^2 + z^2] -> Rdz,
   (R^2 + z^2)^Rational[s : -1 | 1, 2] :> Rcn^s,
   (R^2 + (a + Sqrt[h^2 + z^2])^2)^Rational[s : -3 | 3, 2] :> Rd^s
   };

Note the use of Rational[…, 2] as opposed to …/2 - the problem is that we have to explicitly write out the Rational head, since …/2 does not get converted to a Rational if is not an explicit integer:

Head /@ {
  1/2,
  -1/2,
  (s : -1 | 1)/2,
  Rational[s : -1 | 1, 2]
  }
(* {Rational, Rational, Times, Rational} *)

Now, the replacements work as expected:

VR /. rule
(* -(Lz^2/R^3) + (Md R)/Rd^3 + (Mn R)/(Rcn (Rcn - rs)^2) *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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