Search code examples
pythonrcomplex-numbers

Python vs R/Matlab implementation of exponential of a complex number


I'm facing different results while implementing this simple calculation in Python vs R

e^(2*pi*1j) = cos(2*pi) + j*sin(2*pi) = 1

In R, it gives the expected result

j   <- complex(real = 0, imaginary = 1)
exp(2*pi*j)
>>1 -0j

Whereas in Python

import math
import cmath

cmath.exp(2*math.pi*1j)
>>(1-2.4492935982947064e-16j)
## Also tried this
math.e ** (2*math.pi*1j)
>>(1-2.4492935982947064e-16j)

What am I doing wrong while implementing it in Python?


Solution

  • You're not doing anything wrong. The imaginary parts are tiny, the result of inevitable floating-point imprecision. The difference between R and Python is only in the representation of the output; R (originally designed as a platform for interactive statistical analysis) doesn't show the very small imaginary part, but it's still there:

    j   <- complex(real = 0, imaginary = 1)
    > exp(2*pi*j)
    [1] 1-0i
    > Im(exp(2*pi*j))
    [1] -2.449294e-16
    print(Im(exp(2*pi*j)),digits=22)
    [1] -2.449293598294706414348e-16