4

Can I compile a function that contains ArcTanh[]? The following doesn't work

Needs["CCodeGenerator`"]
c = Compile[ {{x}}, ArcTanh[x]^2];
c[2.5]

Mathematica gives me

"CompiledFunction::cfn: Numerical error encountered at instruction 1;
 proceeding with uncompiled evaluation>>"

However, in the answer to this question, a reply indicates that ArcTanh can be compiled.

Sim Con
  • 41
  • 1
  • 2
    The values of $\tanh x$ are between -1 and 1 for real arguments. If you wish to work with complex numbers, use the appropriate type annotation in Compile[{{x, _Complex}}, ...]. – Szabolcs Sep 23 '13 at 20:10

1 Answers1

13

The values of $\tanh x$ are between -1 and 1 for real arguments. ArcTanh[x] yields a complex answer if x is not between -1 and 1. Compile does support complex numbers, but you need to specify this using a type annotation:

cf = Compile[{{x, _Complex}}, ArcTanh[x]^2];
cf[2.5]

(* ==> -2.28792 - 1.33093 I *)

If you allow for complex inputs in cf, it'll be able to return complex results as well.


Side note: you don't need to load CCodeGenerator` to use Compile.

Szabolcs
  • 234,956
  • 30
  • 623
  • 1,263