-
Notifications
You must be signed in to change notification settings - Fork 0
/
Fourier.py
131 lines (115 loc) · 3.19 KB
/
Fourier.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
import math
import cython
import extract
import cmath
import time
def integrate(exp,downer,upper):
if(upper=='inf'):
upper=100000
if(exp.isnumeric()):
return(int(exp)*(upper-downer))
dx=(upper-downer)/1000
val1=cython.declare(cython.float)
val2=cython.declare(cython.float)
arr=[0]
if(upper==downer):
sum=0.0
elif(upper>downer):
j=downer
sum=0.0
while(j<upper):
arr[0]=j
val1=extract.main(exp,arr)
arr[0]=j+dx
val2=extract.main(exp,arr)
sum+=(val1+val2)/2*dx
j=j+dx
else:
j=upper
sum=0.0
while(j<downer):
arr[0]=j
val1=extract.main(exp,arr)
arr[0]=j-dx
val2=extract.main(exp,arr)
sum+=(val1+val2)/2*dx
j=j-dx
return sum
def CosCoeff(exp,n,p1,p2):
if(p1==-1*math.pi and p2==math.pi):
term=integrate(exp+"cos("+str(n)+"*"+"x)",p1,p2)/(p2-p1)
else:
term=integrate(exp+"cos("+str(n)+"*"+str(math.pi)+"*"+"x/"+str((p2-p1)/2)+")",-p1,p2)/((p2-p1)/2)
if(math.fabs(term)<10e-10):
return 0
else:
return term
def SinCoeff(exp,n,p1,p2):
if(n==0):
return 0
if(p1==-1*math.pi and p2==math.pi):
term=integrate(exp+"sin("+str(n)+"*"+"x)",p1,p2)/((p2-p1)/2)
else:
term=integrate(exp+"sin("+str(n)+"*"+str(math.pi)+"*"+"x/"+str((p2-p1)/2)+")",-p1,p2)/((p2-p1)/2)
if(math.fabs(term)<10e-10):
return 0
else:
return term
def FourierCoeff(exp,n,p1,p2):
real=CosCoeff(exp,math.fabs(n),p1,p2)
imag=SinCoeff(exp,math.fabs(n),p1,p2)
if(n<0):
z=complex(real/2,imag/2)
else:
z=complex(real/2,-1*imag/2)
return z
def discreteFourier(x,n):
if(len(x)==1):
return [x[0]]
else:
e=[]
o=[]
ek=[]
ok=[]
for i in range(int(n/2)):
e.append(x[2*i])
o.append(x[2*i+1])
ek=discreteFourier(e,len(e))
ok=discreteFourier(o,len(o))
y=[None]*n
for i in range(int(n/2)):
y[i]=ek[i]+cmath.rect(1,-1*2*math.pi*i/n)*ok[i]
y[i+int(n/2)]=ek[i]-cmath.rect(1,-1*2*math.pi*i/n)*ok[i]
return y
def inverseFourier(x,n):
if(len(x)==1):
return [x[0]]
else:
e=[]
o=[]
ek=[]
ok=[]
for i in range(int(n/2)):
e.append(x[2*i])
o.append(x[2*i+1])
ek=inverseFourier(e,len(e))
ok=inverseFourier(o,len(o))
y=[None]*n
for i in range(int(n/2)):
y[i]=(ek[i]+cmath.rect(1,2*math.pi*i/n)*ok[i])
y[i+int(n/2)]=(ek[i]-cmath.rect(1,2*math.pi*i/n)*ok[i])
return y
def inverseVal(x,n):
y=inverseFourier(x,n)
try:
for i in range(n):
y[i]=y[i]/n
return y
except:
return("input error")
#x=[]
#for i in range(int(math.pow(2,8))):
# x.append(i)
#t1=time.time()
#print(discreteFourier(inverseVal([1+0j,2+0j,6788+0j,34+0j],4),4))
#print(time.time()-t1)