Browse Source

Add fast polynomial multiplication using FFT

master
arnaucube 2 years ago
parent
commit
64c254bc43
2 changed files with 40 additions and 0 deletions
  1. +20
    -0
      fft.sage
  2. +20
    -0
      fft_test.sage

+ 20
- 0
fft.sage

@ -40,3 +40,23 @@ def fft(F, n):
ft_inv = ft^-1
return w, ft, ft_inv
# Fast polynomial multiplicaton using FFT
def poly_mul(fa, fb, F, n):
w, ft, ft_inv = fft(F, n)
# compute evaluation points from polynomials fa & fb at the roots of unity
a_evals = []
b_evals = []
for i in range(n):
a_evals.append(fa(w[i]))
b_evals.append(fb(w[i]))
# multiply elements in a_evals by b_evals
c_evals = map(operator.mul, a_evals, b_evals)
c_evals = vector(c_evals)
# using FFT, convert the c_evals into fc(x)
fc_coef = c_evals*ft_inv
fc2=P(fc_coef.list())
return fc2, c_evals

+ 20
- 0
fft_test.sage

@ -57,3 +57,23 @@ for i in range(len(a)):
assert fa(w[i]) == a[i]
# Fast polynomial multiplicaton using FFT
print("\n---------")
print("---Fast polynomial multiplication using FFT")
n = 8
# q needs to be a prime, s.t. q-1 is divisible by n
assert (q-1)%n==0
print("q =", q, "n = ", n)
fa=P([1,2,3,4])
fb=P([1,2,3,4])
fc_expected = fa*fb
print("fc expected result:", fc_expected) # expected result
print("fc expected coef", fc_expected.coefficients())
fc, c_evals = poly_mul(fa, fb, F, n)
print("c_evals=(a_evals*b_evals)=", c_evals)
print("fc:", fc)
assert fc_expected == fc

Loading…
Cancel
Save