Can't figure out a recursive function

I have this piece of code to calculate 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 the actual function. d1 and d2 functions that calculate the 1st and 2nd derivatives. They are the ones I'm interested in optimizing. As you can see they both have almost the same code. I could basically keep writing functions like that for 3rd, 4th, etc derivatives, however I'm wondering if it is possible to write it as a single function specifying the derivative level as a parameter.


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 2nd, and so on.

Need Your Help

Generating LaTeX tables instead of text in Rstudio

r latex rstudio

I am new to latex, and would like to generate PDF tables instead of text so my example is:

Flex Air: Read “ActionScript object” from file then cast?

flex object air

It is quite simple to do it, you write the object down to file, then you read it:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.