poly.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. # module 'poly' -- Polynomials
  2. # A polynomial is represented by a list of coefficients, e.g.,
  3. # [1, 10, 5] represents 1*x**0 + 10*x**1 + 5*x**2 (or 1 + 10x + 5x**2).
  4. # There is no way to suppress internal zeros; trailing zeros are
  5. # taken out by normalize().
  6. def normalize(p): # Strip unnecessary zero coefficients
  7. n = len(p)
  8. while n:
  9. if p[n-1]: return p[:n]
  10. n = n-1
  11. return []
  12. def plus(a, b):
  13. if len(a) < len(b): a, b = b, a # make sure a is the longest
  14. res = a[:] # make a copy
  15. for i in range(len(b)):
  16. res[i] = res[i] + b[i]
  17. return normalize(res)
  18. def minus(a, b):
  19. neg_b = map(lambda x: -x, b[:])
  20. return plus(a, neg_b)
  21. def one(power, coeff): # Representation of coeff * x**power
  22. res = []
  23. for i in range(power): res.append(0)
  24. return res + [coeff]
  25. def times(a, b):
  26. res = []
  27. for i in range(len(a)):
  28. for j in range(len(b)):
  29. res = plus(res, one(i+j, a[i]*b[j]))
  30. return res
  31. def power(a, n): # Raise polynomial a to the positive integral power n
  32. if n == 0: return [1]
  33. if n == 1: return a
  34. if n/2*2 == n:
  35. b = power(a, n/2)
  36. return times(b, b)
  37. return times(power(a, n-1), a)
  38. def der(a): # First derivative
  39. res = a[1:]
  40. for i in range(len(res)):
  41. res[i] = res[i] * (i+1)
  42. return res
  43. # Computing a primitive function would require rational arithmetic...