Skip to content
Related Articles

Related Articles

How to Evaluate Polynomial at X and Shape of the Coefficient NumPy Array Extended for Each Dimension

View Discussion
Improve Article
Save Article
  • Last Updated : 09 May, 2022
View Discussion
Improve Article
Save Article

In this article, we will discuss how to evaluate a polynomial at points x and the shape of the coefficient array extended for each dimension of x in Python.

Example:
Input: matrix([[7, 6],
              [2, 3]])
Output: [[ 9. 11.]
         [ 9. 12.]]

We use the polynomial.polyval() function to evaluate a polynomial at locations x in  Python NumPy

Syntax: numpy.polyval(p, x)

Parameters :

  • p : [array_like or poly1D] polynomial coefficients are given in decreasing order of powers. If the second parameter (root) is set to True then array values are the roots of the polynomial equation.
  • x : [array_like or poly1D] A number, an array of numbers, for evaluating ā€˜pā€™.

Return: Evaluated value of polynomial.

The shape of coefficient array ‘Arr’ is expanded by ones on the right, one for each dimension of x, if the third parameter i.e. ‘tensor’ is True. For this action, scalars have no dimension. As a consequence, each element of x is assessed for each column of coefficients in ‘Arr’. If False, for the evaluation, x is disseminated over the columns of ‘Arr’. When ‘Arr’ is multidimensional, this term comes in handy. True is the default state.

Stepwise Implementation

Step 1: Import NumPy 

import numpy as np
from numpy.polynomial.polynomial import polyval

Step 2: Now we have to create a multidimensional array ‘Arr’ of coefficients as shown below :

Arr = np.arange(4).reshape(2,2)

Step 3: To evaluate a polynomial at points x, we use the polynomial.polyval() function in Python Numpy

print("Result : \n",polyval([1,2], Arr, tensor=True))

Example 1 :

Python3




# importing necessary libraries
import numpy as np
from numpy.polynomial.polynomial import polyval
 
# Create a multidimensional array 'Arr'
# of coefficients
Arr = np.matrix([[7,6],[2,3]])
 
# To evaluate a polynomial at points x,
# we use the polynomial.polyval()
# function in Python Numpy
print(polyval([1,2], Arr, tensor=True))

Output :

[[ 9. 11.]
 [ 9. 12.]]

Example 2 :

Python3




# import polyval library from numpy
from numpy.polynomial.polynomial import polyval
 
# create a multidimensional array or matrix
Arr = [[7, 6], [2, 3]]
 
# evaluate polynomial at points x using
# polyval function
print(polyval([1, 2], Arr, tensor=True))

Output :

[[ 9. 11.]
 [ 9. 12.]]

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!