Using Python Lambdas for Fun and Derivatives

von Felix

Today, I have a few lines of code for you:

def derivative(f, h=0.000001):
    return lambda x: (f(x + h) - f(x))/h

sqd = derivative(lambda x: x**2) # first derivative of f(x) = x²
print sqd(12)

Beautiful, isn’t it? Although this is CS101* material, it never ceases to amaze me. (In Scheme this is more aesthetically pleasing, but I thought that more of you would be able to read Python.)

* e.g., Einführung in die Informatik offered by Prof. Guido Wirtz (University of Bamberg)

Kommentieren