Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding the derivative of a polynomial

Tags:

python

math

I wondering symbolically how you would parse a polynomial into a function and return the derivative. What data structure would I use or method to parse the polynomial? Preferably without using any libraries, as this question could pop up in a technical interview.

polynomial-> of nth degree

def derivative(polynomial):
    return derivative

Example:

f(x)  = 2x^2+3x+1
f'(x) = 4x+3

I don't want a solution, this is not homework but a hint of where I would start.

like image 211
Robert Avatar asked Jun 22 '12 11:06

Robert


2 Answers

If the polynomial equation is given as a list. For eg: p=[9,4,12,2] return value will be [27, 8, 12]

     def derivative(p):
        derv=[]
        for i in range(len(p)-1):
            derv.append((len(p)-i-1)*p[i])
        return derv
like image 200
Ujjwal Aryal Avatar answered Oct 14 '22 14:10

Ujjwal Aryal


A polynomial in a single variable can be represented simply as an array containing the coefficients. So for example 1 + 5x3 - 29x5 can be expressed as [1, 0, 0, 5, 0, -29]. Expressed in this form the derivative is easy to compute.

suppose poly is a python list as above. Then

deriv_poly = [poly[i] * i for i in range(1, len(poly))]

For sparse polynomial other representations are relatively easy, such as a list of pairs (coefficient, exponent) or dictionary mapping exponents to coefficients.

Parsing the expression is more complicated but using various parsing frameworks should be easy because the grammar is comparatively simple.

like image 28
President James K. Polk Avatar answered Oct 14 '22 15:10

President James K. Polk