I am trying to port a Mathematica expression to Python and eventually C++ code. I noticed that the expression can have some complex intermediate values, despite the final result always being a real number. I was wondering if there is a way to force Mathematica to simplify the expression to something where no complex numbers are used during the computation. Obviously I could also evaluate complex numbers in C++, but that seems overkill in this case, since it should be possible to do it without.

A simple example of such an expression would be

Simplify[Erf[Sqrt[a]] / Sqrt[a], a < 0]

In this case, Simplify does not manage to further simplify this expression. However, if I slightly rewrite as

Simplify[Erf[Sqrt[-a]] / Sqrt[-a], a > 0]

It is simplified as desired to

Erfi[Sqrt[a]] / Sqrt[a]

This - unsurprisingly - shows that technically Mathematica would know how to simplify these kind of expressions involving error functions and square roots.

I've tried different versions of simplify and different arguments, and sometimes it works, sometimes it does not. The expressions I am trying to simplify are quite a bit more complex and it would be great to know how to use Mathematica to do that.

Is there a way to somehow force Mathematica to avoid complex intermediate values?


1 Answer 1

Erf[Sqrt[a]]/Sqrt[a] == Erfi[Sqrt[-a]]/Sqrt[-a] // FullSimplify

(* True *)

The problems is that you want a result with a higher complexity

LeafCount /@ {Erf[Sqrt[a]]/Sqrt[a], Erfi[Sqrt[-a]]/Sqrt[-a]}

(* {12, 16} *)

Consequently, you need to specify a ComplexityFunction

Assuming[a < 0, 
 Erf[Sqrt[a]]/Sqrt[a] //
    ComplexityFunction -> (100 Count[#, _Erf, {0, Infinity}] + 
        LeafCount[#] &)] &]

(* Erfi[Sqrt[-a]]/Sqrt[-a] *)
  • $\begingroup$ Thanks! That seems to work, in combination with replacing a < 0 by a >0 and flipping the sign of a in the expression. I guess in a way the ideal solution would be to very strongly penalize roots of negative variables in the complexity function. Would that be possible? I.e. Sqrt[-a] should be more desirable than Sqrt[a] if a < 0 (accepting your answer for now since it did help me to solve the problem in my specific case) $\endgroup$
    – delio
    Apr 1, 2020 at 8:03

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.