NumPy: Compute the given polynomial values
Write a NumPy program to compute the following polynomial values.
Sample Solution:
Python Code:
# Importing the NumPy library
import numpy as np
# Computing the value of the polynomial [1, -2, 1] when x = 2
print("Polynomial value when x = 2:")
print(np.polyval([1, -2, 1], 2))
# Computing the value of the polynomial [1, -12, 10, 7, -10] when x = 3
print("Polynomial value when x = 3:")
print(np.polyval([1, -12, 10, 7, -10], 3))
Sample Output:
Polynomial value when x = 2: 1 Polynomial value when x = 3: -142
Explanation:
numpy.polyval(p, x) evaluates the polynomial p at x.
np.polyval([1, -2, 1], 2): Here p = [1, -2, 1], so the polynomial is x^2 - 2x + 1. We evaluate this polynomial at x=2, which gives 2^2 - 2*2 + 1 = 1.
np.polyval([1, -12, 10, 7, -10], 3): Here p = [1, -12, 10, 7, -10], so the polynomial is x^4 - 12x^3 + 10x^2 + 7x - 10. We evaluate this polynomial at x=3, which gives 3^4 - 12*3^3 + 10*3^2 + 7*3 - 10 = -142
Pictorial Presentation:
Python-Numpy Code Editor:
Previous: Write a NumPy program to find the roots of the following polynomials.Next: Write a NumPy program to add one polynomial to another, subtract one polynomial from another, multiply one polynomial by another and divide one polynomial by another.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics