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