Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Add one polynomial to another in Python
To add one polynomial to another in Python, use the numpy.polynomial.polynomial.polyadd() method. This function returns the sum of two polynomials c1 + c2. The arguments are sequences of coefficients from lowest order term to highest, i.e., [1,2,3] represents the polynomial 1 + 2*x + 3*x**2.
The numpy.polynomial.polynomial module provides a number of objects useful for dealing with polynomials, including a Polynomial class that encapsulates the usual arithmetic operations.
Syntax
numpy.polynomial.polynomial.polyadd(c1, c2)
Parameters
The method takes the following parameters ?
- c1, c2 ? 1-D arrays of polynomial coefficients ordered from low to high
Return Value
Returns a 1-D array representing the coefficient array of their sum.
Example
Let's see how to add two polynomials using polyadd() method ?
from numpy.polynomial import polynomial as P
# Declare two polynomials
# p1 represents: 4 + 1*x + 6*x^2
# p2 represents: 2 + 5*x + 3*x^2
p1 = (4, 1, 6)
p2 = (2, 5, 3)
# Display the polynomials
print("Polynomial 1...\n", p1)
print("\nPolynomial 2...\n", p2)
# Add the polynomials
sum_result = P.polyadd(p1, p2)
print("\nResult (Sum)...\n", sum_result)
Polynomial 1... (4, 1, 6) Polynomial 2... (2, 5, 3) Result (Sum)... [6. 6. 9.]
How It Works
The addition works coefficient-wise ?
- Constant term: 4 + 2 = 6
- x coefficient: 1 + 5 = 6
- x² coefficient: 6 + 3 = 9
So (4 + 1*x + 6*x²) + (2 + 5*x + 3*x²) = 6 + 6*x + 9*x²
Adding Polynomials of Different Degrees
The method handles polynomials of different degrees automatically ?
from numpy.polynomial import polynomial as P
# Different degree polynomials
p1 = (1, 2) # 1 + 2*x
p2 = (3, 4, 5) # 3 + 4*x + 5*x^2
result = P.polyadd(p1, p2)
print("Sum of different degree polynomials:", result)
Sum of different degree polynomials: [4. 6. 5.]
Conclusion
The numpy.polynomial.polynomial.polyadd() method provides an efficient way to add polynomials by summing their coefficients element-wise. It automatically handles polynomials of different degrees and returns the result as a NumPy array.
