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
Subtract one polynomial to another in Python
To subtract one polynomial from another in Python, use the numpy.polynomial.polynomial.polysub() method. This function returns the difference 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².
The method returns a coefficient array representing their difference. The parameters c1 and c2 are 1-D arrays of polynomial coefficients ordered from low to high.
Syntax
numpy.polynomial.polynomial.polysub(c1, c2)
Parameters
c1, c2: 1-D arrays of polynomial coefficients ordered from low to high degree.
Example
Let's subtract two polynomials using polysub() ?
from numpy.polynomial import polynomial as P
# Define two polynomials
# p1 represents: 3 + 1*x + 6*x²
# p2 represents: 2 + 7*x + 3*x²
p1 = (3, 1, 6)
p2 = (2, 7, 3)
# Display the polynomials
print("Polynomial 1:", p1)
print("Polynomial 2:", p2)
# Subtract p2 from p1
result = P.polysub(p1, p2)
print("Result (p1 - p2):", result)
Polynomial 1: (3, 1, 6) Polynomial 2: (2, 7, 3) Result (p1 - p2): [ 1. -6. 3.]
How It Works
The subtraction is performed coefficient-wise:
- Constant term: 3 - 2 = 1
- x coefficient: 1 - 7 = -6
- x² coefficient: 6 - 3 = 3
So the result represents: 1 - 6*x + 3*x²
Different Length Polynomials
The method handles polynomials of different degrees automatically ?
from numpy.polynomial import polynomial as P
# Different degree polynomials
p1 = (1, 2, 3, 4) # 1 + 2*x + 3*x² + 4*x³
p2 = (5, 6) # 5 + 6*x
result = P.polysub(p1, p2)
print("Result:", result)
print("Represents: -4 - 4*x + 3*x² + 4*x³")
Result: [-4. -4. 3. 4.] Represents: -4 - 4*x + 3*x² + 4*x³
Conclusion
Use numpy.polynomial.polynomial.polysub() to subtract polynomials coefficient-wise. The function automatically handles polynomials of different degrees and returns the result as a NumPy array.
