Determine recursive derivative calculation in Python

0

I need to create an algorithm to determine in N times the derivative of an X function.

However, I still have some problems to implement recursive functions, I still can not understand logic.

To determine the derivative of the function I'm using:

diff(função)

I was thinking of putting one

for(x = 0; x < VezesUsuario; x++){ derivar } 

But I'm not sure how to return the result of the previous calculation and calculate the derivative of it. I have the requirement to do it recursively, that's my problem indeed.

    
asked by anonymous 26.11.2018 / 18:37

1 answer

4

One of the ways you can do is:

  • Receive in a function diff the function to be derived, f, and the derivation order, N;
  • Calculate the derivative g of order 1 of the function f;
  • If derivation order N equals 1, return the derivative g;
  • Otherwise, return the derivative of order N-1 of the derivative;

So the code would look like:

def diff(func, N=1):
    # Calcula a derivada de ordem 1
    # g = func'

    return g if N == 1 else diff(g, N-1)

So, if you need the second derivative, it will be:

  • The derivative of order 1 will be calculated;
  • As N is greater than 1, the value of the derivative of order 1 of the derivative will be returned;
  • When computing the derivative of the derivative, N will be 1 and the derivative itself will be returned;
  • The final value will be the derivative of order 2 of the input function;

I leave you the challenge of writing a Table Test to calculate the derivative of order 5 or higher.

    
26.11.2018 / 18:54