Search code examples
pythonderivative

How to obtain derivative from a polynomial equation?


I was doing my own method to solve the derivative of the polynomial problem just for fun. But I come up with a problem. I could not delete or remove '*x**2' from array_1 = '3*x**3 + 2*x**2 + 3*x + 5' to obtain an array like this; array = [3, 2, 3, 5].

array_1 = '3*x**3 + 2*x**2 + 3*x + 5'

def converter(array_1):
    array_1 = array_1.split(' + ')

    return str(array_1)

array = [5, 3, 2] # for testing ( I reversed order of an array.)

def derivative(array):
    new_array = []
    for x, elem in enumerate(array):
        z = x*elem
        new_array.append(z)
    return new_array[1:]



result = derivative(array)
print(result)
print(converter(array_1))

Solution

  • Your array is just a string—which is nothing but a sequence of characters. So each elem is just going to be a single character. What you need to do is write a parser.


    For something this simple, you could parse everything with just string operations, or regular expressions if you know how to use them or want to read a tutorial on them. Here's an example with just the methods of the str class:

    s = '3*x**3 + 2*x**2 + 3*x + 5'
    for term in s.split('+'):
        coefficient, _, factor = term.partition('*')
        variable, power = factor.partition('**')
        do_something_with(coefficient, variable, power)
    

    (Of course you probably want to turn the coefficient and power into numbers in that do_something_with code, but that's easy; just use int or float.)

    But this will be somewhat brittle. It'll handle the exact format you have (as long as do_something_with can deal with extra whitespace, and with empty strings for variable and power—just calling int or float can handle the former, but not the latter). But if you try it with, say, 3 * x**3 + 2 * x**2 + 3 * x + 5, it will fail.


    A better option is to use a parsing or parser-generating library. There's a bit of a learning curve, but it's worth doing. For example, pyparsing is a reasonably easy one to learn, there are some great tutorials out there for it, and it comes with extensive examples, one of which I think is pretty close to what you're doing.


    Finally, your format happens to be a subset of Python syntax. You could take advantage of that by using ast, the Python parser that comes with Python. However, this isn't exactly a novice-friendly option.