How to add one polynomial to another using NumPy in Python?
In this article, Let's see how to add one polynomial to another. Two polynomials are given as input and the result is the addition of two polynomials.
- The polynomial p(x) = C3 x2 + C2 x + C1 is represented in NumPy as : ( C1, C2, C3 ) { the coefficients (constants)}.
- Let take two polynomials p(x) and q(x) then add these to get r(x) = p(x) + q(x) as a result of addition of two input polynomials.
If p(x) = A3 x2 + A2 x + A1 and q(x) = B3 x2 + B2 x + B1 then result is r(x) = p(x) + q(x) i.e; r(x) = (A3 + B3) x2 + (A2 + B2) x + (A1 + B1) and output is ( (A1 + B1), (A2 + B2), (A3 + B3) )
Below is the implementation with some examples :
Example 1: simple_use
# importing package
import numpy
# define the polynomials
# p(x) = 5(x**2) + (-2)x +5
px = (5,-2,5)
# q(x) = 2(x**2) + (-5)x +2
qx = (2,-5,2)
# add the polynomials
rx = numpy.polynomial.polynomial.polyadd(px,qx)
# print the resultant polynomial
print(rx)
Output :
[ 7. -7. 7.]
Example 2: #add_with_decimals
# importing package
import numpy
# define the polynomials
# p(x) = 2.2
px = (0,0,2.2)
# q(x) = 9.8(x**2) + 4
qx = (9.8,0,4)
# add the polynomials
rx = numpy.polynomial.polynomial.polyadd(px,qx)
# print the resultant polynomial
print(rx)
Output :
[ 9.8 0. 6.2]
Example 3: eval_then_add
# importing package
import numpy
# define the polynomials
# p(x) = (5/3)x
px = (0,5/3,0)
# q(x) = (-7/4)(x**2) + (9/5)
qx = (-7/4,0,9/5)
# add the polynomials
rx = numpy.polynomial.polynomial.polyadd(px,qx)
# print the resultant polynomial
print(rx)
Output :
[-1.75 1.66666667 1.8 ]