mrAnderson33

КГ Лаба 2(3)

Mar 15th, 2019
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.16 KB | None | 0 0
  1. import matplotlib.pyplot as plot
  2. from matplotlib import mlab
  3. from tkinter.filedialog import askopenfilename
  4. import pylab
  5. import numpy as np
  6. import scipy as sp
  7. from PIL import Image, ImageDraw  
  8. import random, math, copy
  9.  
  10.  
  11. def exp(x):
  12.     a = 0.5
  13.     return math.exp(-(a**2) * (x**2))
  14.  
  15. def fraction(x):
  16.     b = 0.2
  17.     return 1 / (1 + (b**2) * (x**2))
  18.  
  19. def sinFraction(x):
  20.     a = 0.9
  21.     b = 0.6
  22.     return math.sin(a * x) / (1 + (b**2) * (x**2))
  23.  
  24. def myfft(fx):
  25.     fx = np.asarray(fx, dtype=float) #for shape func
  26.     N = fx.shape[0] # len of array
  27.     result = np.zeros(N,dtype=complex) # new array with zero values
  28.     for u in range(N):
  29.         z = np.zeros(2)
  30.         for k in range(N):
  31.             p = 2 * sp.pi * k * u / N
  32.             z[0] += fx[k] * sp.cos(p) + 0 * sp.sin(p) # real part
  33.             z[1] += 0 * sp.cos(p) - fx[k] * sp.sin(p) # imag part
  34.         result[u] = z[0] + z[1]*1j
  35.          
  36.     return result
  37.  
  38. # initialize x = [1, 2, 3, 4 ...]
  39. SIZE = 256
  40. xlist = [0] * SIZE
  41. for i in range(SIZE):
  42.     xlist[i] = i
  43. mode = 2
  44.  
  45. # fx - exponenta
  46. fx = [exp(x) for x in xlist]
  47.  
  48. #if (mode == 1):
  49.     # My fast fourier transform
  50. res = myfft(fx)
  51. pylab.plot (xlist, res.real)
  52. pylab.plot (xlist, res.imag, '--')
  53. pylab.legend ( ("real part", "imagine part"), title = "Exponent (homemade)" )
  54. pylab.show()    
  55. #if (mode == 2):
  56.     # standart fft from Numpy for checking answer
  57. res = np.fft.fft(fx)
  58.  
  59. pylab.plot (xlist, res.real)
  60. pylab.plot (xlist, res.imag, '--')
  61. pylab.legend ( ("real part", "imagine part"), title = "Exponent" )
  62. pylab.show()
  63.  
  64.  
  65. # fx - Fraction
  66. fx = [fraction(x) for x in xlist]
  67.  
  68. if (mode == 1):
  69.     res = myfft(fx)
  70. if (mode == 2):
  71.     res = np.fft.fft(fx)
  72.  
  73. pylab.plot (xlist, res.real)
  74. pylab.plot (xlist, res.imag, '--')
  75. pylab.legend ( ("real part", "imagine part"), title = "Fraction" )
  76. pylab.show()
  77.  
  78.  
  79.  
  80. # fx - Fraction with sinus
  81. fx = [sinFraction(x) for x in xlist]
  82.  
  83. if (mode == 1):
  84.     res = myfft(fx)
  85. if (mode == 2):
  86.     res = np.fft.fft(fx)
  87.  
  88. pylab.plot (xlist, res.real)
  89. pylab.plot (xlist, res.imag,'--')
  90. pylab.legend ( ("real part", "imagine part"), title = "Fraction with sinus" )
  91. pylab.show()
Advertisement
Add Comment
Please, Sign In to add comment