w3resource

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:

NumPy Mathematics: Compute the given polynomial values.

Python-Numpy Code Editor: