Prepare the complex I to subexpression of expression?

Consider the following example:

expr = a (1 + b + cd + Sqrt[-2 de + fg + h^2] + aj ); 

Now I would like to insert complex I in front of the term in the square root and save the rest of the expression. I know that expr has only one member of Sqrt . So I tried the following:

 ToBoxes@ # /. SqrtBox@x _ :> RowBox[{I, " ", SqrtBox@x }] &[ expr] // ToExpression Out[1] = $Failed 

Q1: Why is this failing?

The workaround was to use another variable and then replace it with I as follows:

 ( ToBoxes@ # /. SqrtBox@x _ :> RowBox[{k, " ", SqrtBox@x }] &[expr] // ToExpression) /. k -> I 

enter image description here

Q2: Why does it work?

Q3: Are there any alternative / better ways to do this?

+4
source share
3 answers

Parts of a rectangular expression that are not structural must be strings. So you want

 In[1]:= expr = a (1 + b + cd + Sqrt[-2 de + fg + h^2] + aj ); In[2]:= ToBoxes@ # /. SqrtBox@x _ :> RowBox[{"I", " ", SqrtBox@x }]&[expr]//ToExpression Out[2]= a (1 + b + cd + I Sqrt[-2 de + fg + h^2] + aj) 
+4
source

Errr

 expr /. Sqrt[x_] -> I Sqrt[x] 

?

Edit

If you want to consider case 1 / Sqrt [x], try:

 expr/.Sqrt[x_]->I Sqrt[x]/.Power[x__,Rational[-1,2]]-> 1/( I Sqrt[x]) 
+4
source

Simon is right that you need quotes. In addition, your replacement can be simplified:

 ToBoxes@expr /. x_SqrtBox :> RowBox@ {"I", x} // ToExpression 
+1
source

All Articles