Why is (-1.)^2. a complex number
My original answer (below) is wrong. Arbitrary precision does not fix this problem, I only fooled myself (and others) into thinking that it does. Now please consider:
Power[-1`5, 2`5]
1.0000 + 0.*10^-5 I
This agrees with the output of the effective computation that Daniel described in a comment:
power[base_, pow_] := Exp[pow*Log[base]]
power[-1`5, 2`5]
1.0000 + 0.*10^-5 I
Following that evaluation we get a complex value from Log
when base
is negative:
Log[-1`5]
0.*10^-5 + 3.1416 I
Given the method used complex numbers seem inherent in the calculation.
Mistaken assertion
Round-off errors occur in floating point calculations. You can use arbitrary precision to avoid these:
(-1`5)^2
1.0000
My guess is that when you write 1. and 2. as opposed to 1 and 2 you are telling Mathematica that the numbers you are using are not integers but that they are rather real numbers whose best decimal representation is, as far as you know or within your accuracy criteria, 1.0 and 2.0. Thus, numerical methods are legitimate and you can expect numerical errors.
It is for a similar reason that1+1.
returns 2.
(a real) rather than 2
(integer).
Mathematica is aware of the issue as testified by this example:
Simplify[(-1.)^(2 z), Element[z, Integers]]
(* 1. *)
Simplify[(-1)^(2 z), Element[z, Integers]]
(* 1 *)
lets make a fair fortran test... raise a complex typed number 1 to the power:
write(*,*)(-1.d0,0.d0)**2.,(-1.d0,0.d0)**2
(1.00000000000,-2.449212707...E-16 ) , ( 1.0000000000,0.000000000 )
also note in fortran the real power can not yield a complex result, that is (-1.)**.5
throws an error or yields NaN
depending on the compiler so you see (-1.)**2.
works only because (/if) the compiler is smart enough to recognize that 2.
should be treated as an integer.
**the first test was with the gfortran compiler, intel fortran gives the expected
( 1.0000000000,0.000000000 ) , ( 1.0000000000,0.000000000 )