[Tutor] Polynomial class (a beginning)

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Wed, 23 Jan 2002 16:15:13 -0800 (PST)


On Wed, 23 Jan 2002, Kirby Urner wrote:

>  >>> class Poly:
> 	def __init__(self,coeffs):
> 	    self.coeffs = coeffs
> 	    self.degree = len(self.coeffs)-1
> 	def __repr__(self):
> 	    outstr = ""
> 	    terms = ["+(("+str(self.coeffs[k])+")*x**"+str(self.degree-k)+")" \
> 	             for k in range(len(self.coeffs)) \
> 	             if self.coeffs[k]<>0]
> 	    outstr = reduce(add,terms)
> 	    return outstr
> 	def __call__(self,val):	
> 	    return apply(eval("lambda x:" + self.__repr__()), (val,))
> 
> 	
>  >>> p = Poly([1,2,3])  # enter coefficients of x powers
>  >>> p                  # get back a string representation (kinda messy)
> +((1)*x**2)+((2)*x**1)+((3)*x**0)
>  >>> p(3)               # the string may be evaluated for x = number
> 18


It might be nicer to sort the polynomials by ascending degree --- that
is, to represent something like:

    x^2 + 2x^1 + 3x^0

we can use the list:

    [3, 2, 1]

It might seem... backwards, but it's actually quite useful.  I remember
seeing this representation of polynomials in Jeffrey Ullmans "Fundamentals
of ML Programming", and I thought it was a great demonstration of how data
representation can make a difference.

One reason this is a convenient representation is because finding the sum
of two polynomials becomes pretty easy: we just add corresponding terms
up!

###
    def add(self, other):
        """Adds two polynomials together, assuming the coeffs are
           ordered by ascending degree."""
        sum_terms = [0] * max(len(self.coeffs),
                              len(other.coeffs))
        for i in range(len(self.coeffs)):
            sum_terms[i] = self.coeffs[i]
        for i in range(len(other.coeffs)):
            sum_terms[i] = sum_terms[i] + other.coeffs[i]
        return Poly(sum_terms)
###

(Warning: I haven't tested this code yet.  I'm just typing this from
memory.)


Multiplication, too, can become a much simpler operation if we order the
coefficients this way.  Let's have someone take a stab at that one.  
*grin*


Talk to you later!