Manas Dogra
Manas Dogra

Reputation: 317

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?

Upvotes: 2

Views: 903

Answers (2)

Hamed
Hamed

Reputation: 315

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

Upvotes: 2

Anshul Choudhary
Anshul Choudhary

Reputation: 305

For this task, you have to use python's symbolic module (sympy) since you specifically want your output to be a polynomial representation. The following code should do the job.

import sympy 
from sympy import poly

x = sympy.Symbol('x') # Create a symbol x

coefficients = [1,-2,5] # Your coefficients a python list

p1 = sum(coef*x**i for i, coef in enumerate(reversed(coefficients))) # expression to generate a polynomial from coefficients.

print p1 # print(p1), depending on your python version

This statement: p1.subs('x',2) then evaluates your polynomial 'p1' at x=2.

Upvotes: 0

Related Questions