Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Numpy polyadd() to add two polynomials

Tags:

python

math

numpy

I'm trying to add two polynomials using Numpy's polyadd(), but i'm getting the wrong result

a = [60, 51, 64, 38,  9, 79, 96, 81, 11]
e = [1,0,1,0,1,0,1]
b = np.polyadd(a, e)
b
array([60, 51, 65, 38, 10, 79, 97, 81, 12])

Is there an easy way to get the correct result (61, 51, 65, 38, 10, 79, 97, 81, 11) ?

enter image description here

Numpy treats coefficients from lowest to the highest order right? So here it should be (60+51x+64x^2+38x^3+9x^4+79x^5+96x^6+81x^7+11x^8)+(1+x^2+x^4+x^6) = 61+51x+65x^2+38x^3+10x^4+79x^5+97x^6+81x^7+11x^8

like image 980
Deus Ex Avatar asked Sep 16 '26 19:09

Deus Ex


1 Answers

You are seeing the docs for different function. np.polynomial.polynomial.polyadd uses from lowest order to highest from left to right, whereas, np.polyadd ranks from highest to lowest.

>>> a = [60, 51, 64, 38,  9, 79, 96, 81, 11]
>>> e = [1,0,1,0,1,0,1]
>>> np.polyadd(a, e)
array([60, 51, 65, 38, 10, 79, 97, 81, 12])
>>> np.polynomial.polynomial.polyadd(a,e)
array([61., 51., 65., 38., 10., 79., 97., 81., 11.])

The result you are asking for can be obtained using np.polyadd by reversing the lists and then reversing the obtained result as suggested by @Mad Physicist:

>>> np.polyadd(a[::-1], e[::-1])[::-1]
array([61, 51, 65, 38, 10, 79, 97, 81, 11])
like image 117
Sayandip Dutta Avatar answered Sep 18 '26 08:09

Sayandip Dutta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!