Advertisement
here2share

# fourier_transform.py

Sep 8th, 2023 (edited)
1,435
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.93 KB | None | 0 0
  1. # fourier_transform.py
  2.  
  3. import cmath
  4. import random
  5.        
  6. # Test example
  7. waves = 4000 # the more waves makes for precision
  8. signal = [random.randint(0, 256) for _ in range(waves)]
  9. print(signal, end='\n\n\n')
  10.  
  11. def DFT(x):
  12.     N = len(x)
  13.     return [sum((x[n]*cmath.exp(-2j*cmath.pi*k*n/N) for n in range(N))) for k in range(N)]
  14.  
  15. def fourier_transform(signal):
  16.     # Perform the Fourier transform
  17.     transformed_signal = DFT(signal)
  18.    
  19.     print(transformed_signal[:20], end='\n\n\n')
  20.    
  21.     N = len(transformed_signal)
  22.     for i in range(len(signal)):
  23.         # Perform the inverse Fourier transform
  24.         sum_of_waves = sum((transformed_signal[k]*cmath.exp(2j*cmath.pi*k*i/N) for k in range(N)))
  25.         sum_of_waves = round(sum_of_waves.real) // len(signal)
  26.         valid = sum_of_waves == signal[i]
  27.         oops = ''
  28.         if not valid:
  29.             oops = '!' * 20 + ' '
  30.         print(f'{oops}sum_of_waves: {sum_of_waves} == signal[{i}]: {signal[i]} is {valid}')
  31.  
  32. fourier_transform(signal)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement