nmiculinic
nmiculinic

Reputation: 2474

Pretty printing polynomials in IPython notebook

I have some polynomial x in IPython notebook:

import numpy as np
x = np.polynomial.polynomial.Polynomial([1,2,3])
x

Then x is printed as Polynomial([ 1., 2., 3.], [-1., 1.], [-1., 1.]) which is to be honest ugly. How can I have normal printing like I'm rendering the polynomial in LaTeX or writing it on paper?

Upvotes: 3

Views: 3321

Answers (4)

Næreen
Næreen

Reputation: 1206

Without aiming at a LaTeX output in a IPython notebook, I wrote this small overload of the numpy.polynomial.Polynomial class in order to nicely display a Polynomial object :

>>> P = MyPolynomial  # The custom class, with a modified __str__ method
>>> X = P([0, 1])     # We define the monome X, to write polynomials simply
>>> Q1 = 1 + 2*X + 17*X**3  # Example of a polynomial
>>> # Was displayed poly([1.0, 2.0, 0.0, 17.0]) before... ugly!
>>> print(Q1)  # Way nicer now!
1 + 2 * X + 17 * X**3

By adding a similar _repr_latex_ method, as explained here, for IPython, you could do the same (just change the ** symbols to ^ and remove the *, you will get LaTeX code).

Upvotes: 0

Charles Harris
Charles Harris

Reputation: 984

IPython has an example of how to do this.

Upvotes: 0

Jakob
Jakob

Reputation: 20811

You can use sympy's Poly class to render your polynomials to nice latex. The only issue here, is that numpy lists the coefficients in order of increasing degree, whereas sympy does the opposite.

In [1]: import numpy as np
   ...: nppoly = np.polynomial.polynomial.Polynomial([1,2,3])
   ...: nppoly
Out[1]: Polynomial([ 1.,  2.,  3.], [-1.,  1.], [-1.,  1.])

In [2]: import sympy as sp
   ...: from sympy.abc import x
   ...: sp.init_printing()
   ...: sp.Poly(reversed(nppoly.coef),x).as_expr()

which gives:
enter image description here

Upvotes: 3

ZdaR
ZdaR

Reputation: 22954

You can always retrieve the coefficients of a polynomial object using the polynomial_obj.coef which returns a numpy array and then you can just play around with it to get the desired output.

import numpy as np
x = np.polynomial.polynomial.Polynomial([1,2,3])

def get_prettified_output(polynomial):
    prettified_output = ""
    coefficients = polynomial.coef
    for i in xrange(len(coefficients)):
        prettified_output+= str(coefficients[i])+"*x**"+str(i)+" + "
    return prettified_output[:-2]

print get_prettified_output(x)

However, you can also use something like prettified_output+= str(polynomial.coef[i])+"*x^"+str(i)+" + " or something more convenient.

Upvotes: 0

Related Questions