polynomial.py

Created by emrio

Created on February 12, 2020

624 Bytes

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

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.