w3resource

NumPy: Add, subtract, multiply and divide polynomials

NumPy Mathematics: Exercise-18 with Solution

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.

Sample Solution:

Python Code:

# Importing the required polynomial functions from numpy
from numpy.polynomial import polynomial as P

# Define the coefficients of the first polynomial
x = (10, 20, 30)

# Define the coefficients of the second polynomial
y = (30, 40, 50)

# Add one polynomial to another
print("Add one polynomial to another:")
print(P.polyadd(x, y))

# Subtract one polynomial from another
print("Subtract one polynomial from another:")
print(P.polysub(x, y))

# Multiply one polynomial by another
print("Multiply one polynomial by another:")
print(P.polymul(x, y))

# Divide one polynomial by another
print("Divide one polynomial by another:")
print(P.polydiv(x, y)) 

Sample Output:

Add one polynomial to another:                                         
[ 40.  60.  80.]                                                       
Subtract one polynomial from another:                                  
[-20. -20. -20.]                                                       
Multiply one polynomial by another:                                    
[  300.  1000.  2200.  2200.  1500.]                                   
Divide one polynomial by another:                                      
(array([ 0.6]), array([-8., -4.]))

Pictorial Presentation:

NumPy Mathematics: Add, subtract, multiply and divide polynomials. NumPy Mathematics: Add, subtract, multiply and divide polynomials.

Python-Numpy Code Editor:

Previous: Write a NumPy program to compute the following polynomial values.
Next: Write a NumPy program to calculate mean across dimension, in a 2D numpy array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/numpy/python-numpy-math-exercise-18.php