NumPy: Compute the given polynomial values
17. Evaluate Polynomial Values
Write a NumPy program to compute the following polynomial values.
Sample Solution:
Python Code:
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:
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.
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