开发者

Prepend complex I to a sub-expression of an expression?

Consider this example:

expr = a (1 + b + c d + Sqrt[-2 d e + fg + h^2] + a j );

Now I'd like to insert a complex I before the term in the square root and retain the rest of the expression. I know that expr has only one Sqrt term in it. So I tried the following:

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

Q1: Why does it fail?

The workaround was to use a different variable and then replace it with I as so:

(ToBoxes@# /. SqrtBox@x_ :> RowBox[{k, " ", SqrtB开发者_JAVA技巧ox@x}] &[expr] // 
   ToExpression) /. k -> I 

Prepend complex I to a sub-expression of an expression?

Q2: Why does this work?

Q3: Are there alternate/better ways to do this?


The parts of a box expression that aren't structural need to be strings. So you want

In[1]:= expr = a (1 + b + c d + Sqrt[-2 d e + fg + h^2] + a j );

In[2]:= ToBoxes@# /. SqrtBox@x_ :> RowBox[{"I", " ", SqrtBox@x}]&[expr]//ToExpression
Out[2]= a (1 + b + c d + I Sqrt[-2 d e + fg + h^2] + a j)


Errr

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

?

Edit

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

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


Simon is correct that you need the quote marks. Also, your replacement can be simplified:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜