Why (-1.)^2.
in Mathematica returns a complex number? It looks like in both C and Fortran it returns 1. Why does Mathematica behave differently than the other systems? Is it because the way Mathematica calculates the power is unique compared to others? If this is true then what are the advantages of this design?
I'm curious because it seems cost a "bug" in my code. Sometimes the code is more than 10X slower than other time, and it took me a while to figure out that the problem comes the following function
f[n_] := Compile[{{x, _Real}}, Cos[x]^n]
f[2] /@ Range[0, 4 π, π/10]; // AbsoluteTiming
(* {0.000258, Null} *)
f[2.] /@ Range[0, 4 π, π/10]; // AbsoluteTiming
(* {0.140602, Null} *)
Notice that the second evaluation of f
is much slower than the first, because cos[x]^2.
is treated as a complex function and the uncompiled version is invoked.
Here are some examples from other languages, it looks all of them gives 1 as the answer.
Fortran
C
Python
Matlab/Octave
Chop
to remove the imaginary artifacts. $\endgroup$Im[(-1)^x] == Sin[Pi x]
crosses zero atx=2
, but when using inexact numbers there's always a chance that we'd get a slight deviation from precise zero. It's just numerical error. Why C and Fortran don't do this? If you work with a data type that doesn't support imaginary numbers at all then you can't get imaginary results.pow(-1., 2.01)
isnan
in C. $\endgroup$Sin[2. Pi]
not exact 0? You don't get exact 0 in C++ either $\endgroup$In[2]:= 2.*Log[-1.] Out[2]= 0. + 6.28319 I In[3]:= Exp[%] -16 Out[3]= 1. - 2.44929 10 I
$\endgroup$