w3resource

NumPy: Compute the given polynomial values


17. Evaluate 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.

For more Practice: Solve these Related Problems:

  • Implement a function that evaluates a polynomial at a given value using np.polyval and returns the result.
  • Test the function on multiple input values and verify that the outputs match manual calculations.
  • Create a solution that handles polynomials of varying degrees and returns an array of evaluated values.
  • Compare the np.polyval output with a custom implementation using Horner’s method for efficiency.

Go to:


PREV : Polynomial Roots
NEXT : Polynomial Arithmetic Operations

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.