mirror of
https://github.com/arnaucube/math.git
synced 2026-01-10 16:01:31 +01:00
Add fast polynomial multiplication using FFT
This commit is contained in:
20
fft.sage
20
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
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user