You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
1.6 KiB

  1. load("fft.sage")
  2. #####
  3. # Roots of Unity test:
  4. q = 17
  5. F = GF(q)
  6. n = 4
  7. g, primitive_w = get_primitive_root_of_unity(F, n)
  8. print("generator:", g)
  9. print("primitive_w:", primitive_w)
  10. w = get_nth_roots_of_unity(n, primitive_w)
  11. print(f"{n}th roots of unity: {w}")
  12. assert w == [1, 13, 16, 4]
  13. #####
  14. # FFT test:
  15. def isprime(num):
  16. for n in range(2,int(num^1/2)+1):
  17. if num%n==0:
  18. return False
  19. return True
  20. # list valid values for q
  21. for i in range(20):
  22. if isprime(8*i+1):
  23. print("q =", 8*i+1)
  24. q = 41
  25. F = GF(q)
  26. n = 4
  27. # q needs to be a prime, s.t. q-1 is divisible by n
  28. assert (q-1)%n==0
  29. print("q =", q, "n = ", n)
  30. # ft: Vandermonde matrix for the nth roots of unity
  31. w, ft, ft_inv = fft(F, n)
  32. print("nth roots of unity:", w)
  33. print("Vandermonde matrix:")
  34. print(ft)
  35. a = vector([3,4,5,9])
  36. print("a:", a)
  37. # interpolate f_a(x)
  38. fa_coef = ft_inv * a
  39. print("fa_coef:", fa_coef)
  40. P.<x> = PolynomialRing(F)
  41. fa = P(list(fa_coef))
  42. print("f_a(x):", fa)
  43. # check that evaluating fa(x) at the roots of unity returns the expected values of a
  44. for i in range(len(a)):
  45. assert fa(w[i]) == a[i]
  46. # Fast polynomial multiplicaton using FFT
  47. print("\n---------")
  48. print("---Fast polynomial multiplication using FFT")
  49. n = 8
  50. # q needs to be a prime, s.t. q-1 is divisible by n
  51. assert (q-1)%n==0
  52. print("q =", q, "n = ", n)
  53. fa=P([1,2,3,4])
  54. fb=P([1,2,3,4])
  55. fc_expected = fa*fb
  56. print("fc expected result:", fc_expected) # expected result
  57. print("fc expected coef", fc_expected.coefficients())
  58. fc, c_evals = poly_mul(fa, fb, F, n)
  59. print("c_evals=(a_evals*b_evals)=", c_evals)
  60. print("fc:", fc)
  61. assert fc_expected == fc