Using Python Lambdas for Fun and Derivatives
Mittwoch, 29. Februar 2012, 11:11 Uhr von Felix
Today, I have a few lines of code for you:
1.
def
derivative(f, h
=
0.000001
):
2.
return
lambda
x: (f(x
+
h)
-
f(x))
/
h
3.
4.
sqd
=
derivative(
lambda
x: x
*
*
2
)
# first derivative of f(x) = x²
5.
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)