Functions for dealing with polynomials and other functions
polynomial(a1, a2, a3, ...)
: defines a polynomial function by its (real) coefficients
growth_rate(f, a)
: Get the growth rate of the function f
at x = a
newton(f, a)
: Get a root (number x where f(x) = 0) of the function f
starting at x = a
find_roots(a1, a2, a3, ...)
: Gives the approximate values of the roots of a polynomial function described by its (real) coefficients.
Note: this does not work with constant functions!
from math import sqrt def polynomial (*a): return lambda x:sum([a[len(a)-1-i]*x**i for i in range(len(a))]) def reduce(f,l,s): for e in l: s=f(s,e) return s def growth_rate(f,a,dx=0.001): return(f(a+dx)-f(a-dx))/(dx*2) def newton(f,a,steps=500,dx=0.001): for _ in range(abs(steps)+1): a=-f(a)/growth_rate(f,a,dx)+a return a def find_roots(*p): if p[-1]==0:return[0.]+find_roots(*p[:-1]) roots=[] f=lambda x:polynomial(*p)(x)/reduce(lambda a,c:polynomial(1,-c)(x)*a,roots,1) for _ in range(10): a=newton(f,0) if abs(f(a))>0.1:break roots.append(a) return roots