2
$\begingroup$

I need to define a function that takes an input and if and only if its a positive real, outputs the input. If not, the output should be 0. The input could be complex valued or indeterminate.

Heres what I defined;

myMax[x_] := 
  Module[{}, 
   If[x === Indeterminate, 0, If[Element[x, Reals], Max[0, x], 0]]];

This function is not compilable efficiently in mathematica. Is it possible to define such a function using just compilable functions?

$\endgroup$
1
  • 1
    $\begingroup$ What do you mean "not compilable efficiently"? Would this work? myMax = Compile[{{x, _Complex}}, If[Im@x==0, Max[Re@x, 0], 0]]? $\endgroup$ Commented Aug 18, 2023 at 15:29

1 Answer 1

3
$\begingroup$

Not sure if this is the most efficient way, but it should work as expected and is also compilable:

If[Re[x] > 0 && Im[x] == 0, x, 0]

Note that Indeterminate is a Mathematica construct and cannot be used inside a compilable function without reverting back to the main kernel. For example, see the error messages if you do:

Compile[{x, y}, x/y][0, 0]
(*Indeterminate*)

CompiledFunction::cfne: Numerical error encountered; proceeding with uncompiled evaluation.

Power::infy: Infinite expression 1/0. encountered.

Infinity::indet: Indeterminate expression 0. ComplexInfinity encountered.

Therefore, if you expect that Indeterminate could happen in your code, it is best to check the values of arguments before executing a possibly dangerous operation, for example (giving 0 for problematic numbers as in your case):

Compile[{x, y}, If[y == 0, 0, x/y]][0, 0]
(* 0. *)
$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.