Search code examples
pythonpython-2.7symbolic-mathpolynomial-mathpolynomials

How to print string representation of a nth degree polynomial whose co-efficients are known in Python?


Suppose i have the coefficients of a polynomial.How to write it in the usual form we write in pen and paper?E.g. if i have coefficients=1,-2,5 and the polynomial is a quadratic one then the program should print x**2-2*x+5. 1*x**2-2*x**1+5*x**0 will also do.It is preferable that the program is written such that it works for large n too,like order 20 or 30 of the polynomial,and also there is some way to put some value of x into the result.e.g.If i set x=0,in the abovementioned example it should return 5.

So far,i have come to know that the thing i am asking for is symbolic computation,and there is a readymade package in python called sympy for doing these,but by only using the functions,i could not gain insight into the logic of writing the function,i referred to the lengthy source codes of the several functions in sympy module and got totally confused.Is there a simple way to do this probably without using of direct symbolic math packages?


Solution

  • Here is a program that would work, without using the external packages. I have defined a Poly class and it has two methods: 1) evaluation 2) print the polynomial.

    class Poly():
        def __init__(self, coeff):
            self.coeff = coeff
            self.N = len(coeff)
    
        def evaluate(self, x):
            res = 0.0
            for i in range(self.N):
                res += self.coeff[i] * (x**(self.N-i-1))
            return res
    
        def printPoly(self):
            for i in range(self.N):
                if i == self.N-1:
                    print("%f" % (abs(self.coeff[i])))
                else:
                    if self.coeff[i] != 0.0:
                        print("%f * x**%d" % (abs(self.coeff[i]), self.N-i-1), end='')
                        if self.coeff[i+1] > 0:
                            print(" + ", end='')
                        else:
                            print(" - ", end='')
    
    p = poly([1,-2,5]) # creating the polynomial object.
    p.printPoly() # prints: 1.0 * x**2 - 2.0 * x**1 + 5
    print(p.evaluate(0.0)) # prints: 5.0