Search code examples
pythonfftcomplex-numbersdft

Calculating nth Roots of Unity in Python


So, I'm trying to write an algorithm croot(k, n), that returns the kth root of unity with n == n. I'm getting mostly the right answer, however it's giving me really weird representations that seem wrong for certain numbers. Here is an example.

import cmath

def croot(k, n):
    if n<=0:
        return None
    return cmath.exp((2 * cmath.pi * 1j * k) / n)


for k in range(8):
    print croot(k, 8)

Output is:

(1+0j)
(0.70710...+0.70710...j)
(6.12323399574e-17+1j)

Whoa whoa whoa. So the root when k = 2 and n = 8 is wrong, as it should just be i, which would be represented like 1j, or j, or 1.00000j, etc. Could somebody help me here? I'm doing this because I'm trying to write an FFT algorithm. I'm not very experienced with complex numbers and Python so I could very well be making a simple mistake.

Thanks,

If you guys need any additional information just ask.


Solution

  • Look at this number

    (6.12303176911e-17+1j)
    

    6.12303176911e-17 = 0.0000000000000000612303176911 which is really small (close to zero). What you are seeing is rounding errors due to the limited representation of floating point numbers

    The error is equivalent to measuring the distance to the sun to within 10 microns or so. If you're running FFTs on data from the real world the measurement errors are usually far larger than this.