How to use python to find all the roots of a polynomial function? My code below works if all the coefficients a, b, c, d, e
in the my_func
function are removed, that is, if they are equal to 1. How could I edit the code so that a, b, c, d, e
(the arguments in the polynomial_root function) are defined in the said function?
Code:
import numpy as np
def polynomial_root(a,b,c,d,e):
p = np.poly1d([a,b,c,d,e])
roots = p.roots
return roots
def my_func(x):
return a*x**4 + b*x**3 - c*x**2 + d*x - e
def print_format(x, f):
for i in range(0,4):
print("x={}\t\t f(x)={}\t\t".format(x[i],f(x[i])))
# Working with polynomials 8x**4 + 3x**3 - 2x**2 + 8x - 2
c = polynomial_root(8.,3.,-2.,8.,-2)
print("The solutions of f(x) = 8x**4 + 3x**3 - 2x**2 + 8x - 2 are:")
print_format(c, my_func)
in your implementation of my_func
, there are two problems:
a
, b
, c
, d
and e
as if they were global variables, but anywhere else you pass those coefficients as parametersc
and e
, therefore evaluating a different polynomiala fixed version of your code could look like this:
import numpy as np
def polynomial_root(coefficients):
p = np.poly1d(coefficients)
return p.roots
def evaluate_polynomial(coefficients, x):
result = 0
for c, power in enumerate(reversed(coefficients)):
result += c * x**power
return result
def print_format(x_values, coefficients, f):
for x in x_values:
print("x={}\t\t f(x)={}\t\t".format(x, f(coefficients, x)))
# Working with polynomials 8x**4 + 3x**3 - 2x**2 + 8x - 2
coefficients = [8.,3.,-2.,8.,-2]
roots = polynomial_root(coefficients)
print("The solutions of f(x) = {}x**4 + {}x**3 + {}x**2 + {}x + {} = 0 are:".format(coefficients))
print_format(roots, coefficients, evaluate_polynomial)