2021-11-01_playing-with-polynomials.html
001|
002|
003|
004|
005|
006| def build_quadratic_function (a, b, c):
007| """Returns f(x) = ax^2 + bx + c"""
008| return lambda x: a*x**2 + b*x + c
009|
010|
011| quadfunc = lambda a,b,c: lambda x:((a*x*x)+(b*x)+(c))
012|
013|
014| def polyn (coeffs):
015| '''Generate a polynomial function.'''
016|
017| poly1 = lambda c,e:lambda x:(c*pow(x,e))
018|
019|
020| terms = [poly1(c,ix) for ix,c in enumerate(reversed(coeffs))]
021|
022|
023| return lambda x:[f(x) for f in reversed(terms)]
024|
025|
026|
027| f = polyn([1,0,0])
028|
029|
030| terms = [sum(f(x)) for x in range(5)]
031| print(terms)
032|
033|
034| def divisions (start, stop, steps):
035| '''Return list of numbers with N steps.'''
036| s0 = float(start)
037| s1 = float(stop)
038| sx = int(steps)
039|
040| assert (s0 < s1)
041| assert (0 < sx)
042|
043| interval = (s1 - s0) / float(sx)
044|
045| return [s0+(interval*n) for n in range(sx+1)]
046|
047|
048| def intervals (start, stop, interval):
049| '''Return list of numbers by X interval.'''
050| s0 = float(start)
051| s1 = float(stop)
052| sx = float(interval)
053|
054| assert (s0 < s1)
055| assert (0 < sx)
056|
057| acc = [s0]
058|
059| while True:
060| x = acc[-1] + sx
061| if s1 < x: break
062| acc.append(x)
063| return acc
064|
065|
066| class PolyN (object):
067| def __init__ (self, coeffs):
068| ''''Create a new polynomial object.'''
069|
070| poly = lambda c,e:lambda x:(c*pow(x,e))
071|
072| _coeffs = enumerate(reversed(coeffs))
073| terms = [poly(c,ix) for ix,c in _coeffs]
074|
075| self.coeffs = coeffs
076|
077| self.expr = lambda x:[f(x) for f in reversed(terms)]
078|
079| self(0)
080|
081| def __call__ (self, x):
082| '''Evaluate f(x); return result.'''
083|
084| self.vals = self.expr(x)
085|
086| self.result = sum(self.vals)
087| return self.result
088|
089| def __str__ (self):
090| '''Pretty print the polynomial.'''
091| cs = enumerate(reversed(self.coeffs))
092| ts = ['(%+.2f)x^%d' % (c,ix) for ix,c in cs]
093| return ' '.join(reversed(ts))
094|
095| def __repr__ (self):
096| '''Return the coefficients as a string.'''
097| return str(self.coeffs)
098|
099|
100|
101| ftn = PolyN(coefficients)
102|
103|
104| xs = interval(xmin, xmax, incr)
105|
106|
107| ys = [ftn(x) for x in xs]
108|
109|
110|