So I was trying to get e^(pi*I)=-1
, but python 3 gives me another, weird result:
print(cmath.exp(cmath.pi * cmath.sqrt(-1)))
Result:
(-1+1.2246467991473532e-16j)
This should in theory return -1, no?
So I was trying to get e^(pi*I)=-1
, but python 3 gives me another, weird result:
print(cmath.exp(cmath.pi * cmath.sqrt(-1)))
Result:
(-1+1.2246467991473532e-16j)
This should in theory return -1, no?
(Partial answer to the revised question.)
In theory, the result should be -1
, but in practice the theory is slightly wrong.
The cmath
unit uses floating-point variables to do its calculations--one float value for the real part of a complex number and another float value for the imaginary part. Therefore the unit experiences the limitations of floating point math. For more on those limitations, see the canonical question Is floating point math broken?.
In brief, floating point values are usually mere approximations to real values. The value of cmath.pi
is not actually pi, it is just the best approximation that will fit into the floating-point unit of many computers. So you are not really calculating e^(pi*I)
, just an approximation of it. The returned value has the exact, correct real part, -1
, which is somewhat surprising to me. The imaginary part "should be" zero, but the actual result agrees with zero to 15 decimal places, or over 15 significant digits compared to the start value. That is the usual precision for floating point.
If you require exact answers, you should not be working with floating point values. Perhaps you should try an algebraic solution, such as the sympy
module.
(The following was my original answer, which applied to the previous version of the question, where the result was an error message.)
The error message shows that you did not type what you thought you typed. Instead of cmath.exp
on the outside of the expression, you typed math.exp
. The math
version of the exponential function expects a float value. You gave it a complex value (cmath.pi * cmath.sqrt(-1)
) so Python thought you wanted to convert that complex value to float.
When I type the expression you give at the top of your question, with the cmath
properly typed, I get the result
(-1+1.2246467991473532e-16j)
which is very close to the desired value of -1
.
Found the answer. First of all, python 3 cannot properly compute irrational numbers, and so e^(pi*I) will not return -1, as per This answer Secondly, python 3 returns any complex number as a cartesian pair (real + imaginary).
The fix was to extract the real part of the number:
print(cmath.exp(cmath.pi * cmath.sqrt(-1)).real)