Unable to compute recursive function

I have this piece of code to calculate the first and second derivatives of a function at a given point

def yy(x): return 1.0*x*x def d1(func, x ,e): x = x y = func(x) x1 = x + e y1 = func(x1) return 1.0*(y - y1)/(x - x1) def d2(func ,x, e): x = x y = d1(func, x, e) x1 = x + e y1 = d1(func, x1, e) return 1.0*(y - y1)/(x - x1) 

yy is a valid function. d1 and d2, which calculate the 1st and 2nd derivatives. These are the ones I want to optimize. As you can see, they both have almost the same code. I could continue to write such functions for the 3rd, 4th, etc. Derivatives, however, I wonder if it is possible to write it as a single function that determines the level of the derivative as a parameter.

+4
source share
2 answers
 def deriv(func, order, x, e): if order < 0: raise ValueError if order == 0: return func(x) y = deriv(func, order-1, x, e) x1 = x + e y1 = deriv(func, order-1, x1, e) return float(y - y1)/(x - x1) 

order = 1 gives the first derivative, order = 2 gives the second, etc.

+4
source

Try this where lvl is the derivative level.

 def d(func, x ,e, lvl): x1 = x + e if lvl == 1: x = x y = func(x) y1 = func(x1) return 1.0*(y - y1)/(x - x1) else: return 1.0*(d(func, x, e, lvl-1) - d(func, x1, e, lvl-1) )/(x-x1) 
+1
source

All Articles