Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Thought this is a rather simple thing, but I was not able to find a solution: I have a polynomial expression like:

 expr1=a^2-b+c*d
 expr2=a-b
 expr3=-a+b-c

and i want to replace every negative sign to Plus

 expr1new=a^2+b+c*d
 expr2new=a+b
 expr3=a+b+c

The problem is that

FullForm[a-b]
(* Plus[a, Times[-1, b]] *)

thus I cannot use simple replacement. Do you know a simple way for that?

Update This example does not work with simple replacements:

expr4 = (1 - I) a;
expr4 /. {-1 -> 1}
FullForm[expr4]

(* (1 - I) a
Times[Complex[1, -1], a] *)
share|improve this question
1  
Do you really mean every minus? So given this input expr = a - b + Sqrt[-x]; which can be complex depending on x, you want the output to become real (depending on x)? as in expr = a + b + Sqrt[x]; –  Nasser Apr 13 at 15:20
    
@Kuba: Thanks, i was not careful. I added the example which does not work for me. –  NicoDean Apr 13 at 15:24
    
@Nasser: I only use complex multivariable polynomial expressions. (thanks, I added the note). –  NicoDean Apr 13 at 15:25

2 Answers 2

up vote 4 down vote accepted

You have found the snags and you're right -- it's a simple matter. You just need the right rules.

For a pure symbolic expression you can use Kuba's suggestion.

a^2 - b + c*d /. -1 -> 1
a^2 + b + c d

For dealing with complex numbers you can use

(1 - b I) a /. x_Complex /; Im[x] < 0 -> Conjugate[x]
(1 + b I) a

If your expressions are more complicated than these, you might need more elaborate rules. But I offer more without knowing what form the more complicated expression take.

share|improve this answer
    
Nice trick, decomposing the complex into Re and Im. This works. And it can be generalized to: expr = expr /. {x_Complex /; Re[x] < 0 -> -Conjugate[x], Im[x] < 0 -> Conjugate[x], -1 -> 1} - that seems to work for all cases. Thanks. –  NicoDean Apr 13 at 15:46

Allways you can use pattern replace

expr1 = a^2 - b + c*d
expr2 = a - b
expr3 = -a + b - c

expr/. Times[-1, x_] :> Times[1, x]

(*
a^2 + b + c * d
a + b
a + b + c
*)
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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