In: Computer Science
Write a pyhton program and to evaluate polynomials in general and test it on the following: ? 4 − 3? 3 − 39? 2 + 47? + 170 = 0
a) Develop and test a function named evalPoly() that evaluates a polynomial at a given value of the variable. The function receives two arguments: a list of the polynomial coefficients, and the value of the variable. It returns the result of the evaluation as a float. Use your function to evaluate the polynomial at ? = -5.2, -5.0, -1.8, -1.6, 2.6, 2.8, 7.0 and 7.2. What do you conclude about the solutions to the equation above?
b) Write a second function named solvePoly() that seeks a solution of the polynomial between two values of the variable where the function has changed sign. This function should receive the list of coefficients, the two values of the variable between which there is a solution. It should return the value of the variable at which a solution was found. This function may be based on an exhaustive search, a bisection search, or on Newton-Raphson’s method. Select a method with some justification.
Here is the code:
import numpy as np
# 1) Write a pyhton program and to evaluate polynomials in general and
# test it on the following: ? 4 − 3? 3 − 39? 2 + 47? + 170 = 0
poly_result = np.poly1d([1,-3,-39,47,170])
poly_result
# a) Develop and test a function named evalPoly() that evaluates a polynomial at a given value of the variable
# The function receives two arguments: a list of the polynomial coefficients, and the value of the variable.
def evalPoly(coeff,variable):
poly = np.poly1d(coeff)
poly_result = poly(variable)
return(poly_result)
# Use your function to evaluate the polynomial at ? = -5.2, -5.0, -1.8, -1.6, 2.6, 2.8, 7.0 and 7.2
x = [-5.2, -5.0, -1.8, -1.6, 2.6, 2.8, 7.0, 7.2]
coeff = [1,-3,-39,47,170]
result = list()
for item in x:
result.append(evalPoly(coeff,item))
print(evalPoly(coeff,item))
import matplotlib.pyplot as plt # plotting the results
plt.plot(result, x)
# Conclustion: results are varying between positive and negative axes
# Write a second function named solvePoly() that seeks a solution of the polynomial
# between two values of the variable where the function has changed sign.
# This function should receive the list of coefficients, the two values of the variable between which there is a solution
def solvePoly(coeff,value1,value2):
poly = np.poly1d(coeff)
poly_result1 = poly(value1)
while(True):
poly_result2 = poly(value1)
value1 += 0.2 # This function is based on an exhaustive search
poly_result1 = poly(value1)
if(poly_result1 < 0 and poly_result2 > 0):
return(value1-0.2) # It should return the value of the variable at which a solution was found.
# calling the function
solvePoly(coeff,-1.8, -1.6)
Here is the results: