1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
#!/usr/bin/env python

import pylab

VERBOSE=False

class Polynom:
    """My polynomial calculates:
    
    - function value
    - sums of polynomials
    - derivatives
    - integral
    - roots"""
    
    coeff = None
    nullstellen = None
    # default_x: lower limit, upper limit, steps per interval, tolerance
    default_x = [-10.,10.,100,1e-10]
    poly_func = lambda x: 0
    name = '0'
    
    def __call__(self,x):
        """This one of Python's sepcial methods. Play with this script 
to find out, what's so special about this method."""

        return self.poly_func(x)
    
    def __init__(self,c):
        """Coefficients are passed as a sequence during init"""
        
        self.coeff = []
        
        if type(c) == type([]) or type(c) == type(()):
            for C in c:
                self.coeff.append(C)
        elif type(c) == type(1) or type(c) == type(1.):
            self.coeff.append(c)
        else:
            raise TypeError, 'Int or sequence of Int expected, got: %s' % str(type(c))
        self.set_func()

    def __add__(self,other):
        "We can add polynomials"
        
        a = self.coeff[::-1]
        b = other.coeff[::-1]
        print a,b
        
        c = []
        al,bl = len(a),len(b)
        for i in range(min(al,bl)):
            c.append(a[i]+b[i])
        if al>bl:
            for i in range(bl,al):
                c.append(a[i])
        elif bl>al:
            for i in range(al,bl):
                c.append(b[i])
        else:
            pass
        return Polynom(c[::-1])
        
    def __str__(self):
        return 'Polynom: %s' % self.name

    def get_coeff(self):
        return self.coeff
        
    def set_func(self):
        """For mathematics coefficients are converted to a function"""
        f = []
        for n in range(len(self.coeff)):
            f.append('%+.6g * x**%d' % (self.coeff[n],len(self.coeff)-n-1))
        self.name = ' '.join(f)
        if VERBOSE: print self.name
        self.poly_func = eval('lambda x: '+ self.name)
        
    def derive(self,order=1):
        for o in range(order):
            L = len(self.coeff)
            new_coeff = [0 for i in range(L-1)]
            for i in range(L-1,-1,-1):
                try:
                    new_coeff[i] = self.coeff[i]*float(L-i-1)
                except:
                    pass
        return Polynom(new_coeff)

    def integrate(self,order=1,const=0):
        for o in range(order):
            L = len(self.coeff)
            new_coeff = [const for i in range(L+1)]
            for i in range(L-1,-1,-1):
                #try:
                if self.coeff[i] == 0: continue
                new_coeff[i] = self.coeff[i]*1/float(L-i)
                #except:
                    #new_coeff[i] = 0
                print i, new_coeff[i],L-i
        return Polynom(new_coeff)

    def find_nullst(self,a,b):
        """Recursive method for determining roots"""
        x = a
        delta = (b-a)/float(self.default_x[2])
        last_y = None
        for i in range(self.default_x[2]):
            x += delta
            y = self.poly_func(x)
            #if VERBOSE:    print "%05.3f %06.3f" % (x,y)
            if last_y:
                if (last_y > 0 and y < 0) or (last_y < 0 and y > 0):
                    if VERBOSE: print "Nullstelle zwischen %05.3f und %05.3f" % (x-delta,x)
                    if abs(y-last_y)<self.default_x[3]:
                        return x
                    else:
                        if VERBOSE: print "recuring ..."
                        return self.find_nullst(x-delta,x)
            last_y = y
        else:
            return None
        
    def cal_nullst(self):
        """Default method for determining roots. Returns list of roots."""
        if type(self.nullstellen) == type([]):
            del self.nullstellen[:]
        else:
            self.nullstellen = []
            
        nullst = self.default_x[0]
        while True:
            nullst = self.find_nullst(nullst,self.default_x[1])
            if nullst: 
                self.nullstellen.append(nullst)
            else:
                if VERBOSE: print "nichts zurueck gegeben!"
                break
             
        print "Nullstellen:"
        for n in self.nullstellen:  
            print "%+08e %+08e" % (n, self.poly_func(n))
                
        return self.nullstellen
        
    def show(self):
        "Plotting a polynomial is always nice."
        
        x = pylab.arange(self.default_x[0],self.default_x[1],.01)
        y = self.poly_func(x)
        pylab.plot(x,y)
        pylab.grid()
        pylab.show()
            
if __name__ == '__main__':
    p = Polynom([3,-12,2,-3])
    q = pylab.poly1d([3,-12,2,-3])
    print p
    print p.integrate()
    print pylab.polyint(q)
    print p(2.) # here the method __call__ of p is called!