3

I'm trying to evaluate a series of expressions, which, given a set of parameters, may be complex. Instead of throwing a CompiledFunction::cfn, I'm trying to catch it from within and reset it to some default value. Example:

cf = With[{NOTREAL = -1}, Compile[{{x, _Real}}, {Sqrt[x], Sqrt[-x]}]]
cf[100]

I want the return to be {10, -1} without invoking uncompiled function or MainEvaluate. If I used "RuntimeOptions" per Catching error in middle of evaluation of compiled function, the error would still be thrown and the evaluation wil be aborted. Is it possible to tell Mathematica to not evaluate when it sees a non-numeric value coming up and hand it over to some handler? And in reality Sqrt[x] will be replaced with some complicated function. Reduce can't figure out when it'll be real.

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
arax
  • 1,831
  • 12
  • 16

1 Answers1

3

Thanks to @HenrikSchumacher 's comment, I came up with the following

cf = With[{NOTREAL = -1}, Compile[{{x, _Real}},
   Module[{cx = I},
    cx = x;
    If[Abs[Im@#] > 1.*^-12, NOTREAL, Re@#] & /@ {Sqrt[-cx], Sqrt[cx]}]]
  ]

CompilePrint shows that this forces Mathematica to recognize the result of Sqrt as complex, avoiding numerical exception.

arax
  • 1,831
  • 12
  • 16