Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # fourier_transform.py
- import cmath
- import random
- # Test example
- waves = 4000 # the more waves makes for precision
- signal = [random.randint(0, 256) for _ in range(waves)]
- print(signal, end='\n\n\n')
- def DFT(x):
- N = len(x)
- return [sum((x[n]*cmath.exp(-2j*cmath.pi*k*n/N) for n in range(N))) for k in range(N)]
- def fourier_transform(signal):
- # Perform the Fourier transform
- transformed_signal = DFT(signal)
- print(transformed_signal[:20], end='\n\n\n')
- N = len(transformed_signal)
- for i in range(len(signal)):
- # Perform the inverse Fourier transform
- sum_of_waves = sum((transformed_signal[k]*cmath.exp(2j*cmath.pi*k*i/N) for k in range(N)))
- sum_of_waves = round(sum_of_waves.real) // len(signal)
- valid = sum_of_waves == signal[i]
- oops = ''
- if not valid:
- oops = '!' * 20 + ' '
- print(f'{oops}sum_of_waves: {sum_of_waves} == signal[{i}]: {signal[i]} is {valid}')
- fourier_transform(signal)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement