faqts : Computers : Programming : Languages : Python : Language and Syntax

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

Entry

how do you write a program that differentiates polynomials if i already have the polynomial class

Nov 17th, 2004 13:43
stephen brown, Geraldine Burke,


It depends on where you got the polynomial class.  If you
use the poly1d class from scipy_base, then it's already got
a deriv() method.  If you got the class from somewhere else,
consult the documentation for that class.
If you wrote your own, and you want to know how to differentiate
in your own, well it's really a calculus question, not a python
one, but here's the answer for one-variable polynomials.  If
c is a list of the coefficients, highest order first (so c=[1, 0, 0]
is the polynomial f(x)=x^2), then
    d=[c[p]*(len(c)-p-1) for p in range(len(c)-1)]
will set d to the coefficients of df/dx
To use it in a class:
class Polynomial:
    """One variable polynomials.
    Class has one attribute, c, a list of coefficients,
    and one method, deriv(), takes the derivative"""
    def __init__(self, coeffs):
        self.c = coeffs
    def deriv(self):
        return Polynomial([self.c[p]*(len(self.c)-p-1) for p in
range(len(self.c)-1)])
f = Polynomial([1, 0, 0])
df = f.deriv()
ddf = df.deriv()
>>> f.c
[1, 0, 0]
>>> df.c
[2, 0]
>>> ddf.c
[2]
>>>
If you're doing multivariate polynomials, then you need to be
a lot more specific.