Skip to content
Skip to search
1,747 bytes added
03:21, 6 March 2009
Example of creating the derivative function of any function.
The above is an extract from a clojure GUI for XMMS2, available at github [http://github.com/acardona/xmms2-clj/tree xmms2-gui].
<h3>Creating a derivative of a function</h3>
The derivative of a function:
f (x + dx) - f (x)
D f(x) = f'(x) = lim --------------------
We can approximate the derivative by choosing an arbitrarily precise value of the increment <i>dx</i>.
So first we define a function that takes any function as argument and returns a new function that implements its derivative. For convenience, we define it within a closure that specifies the arbitrarily precise increment <i>dx</i> (but we could just pass it as argument):
(let [dx (double 0.0001)]
(defn derivative [f]
"Return a function that is the derivative of the given function f, using dx increments."
(fn f-prime [x]
(/ (- (f (+ (double x) dx))
Then, for any example function like the cube of x:
(defn cubic [x]
(let [a (double x)]
(* a a a)))
... we create its derivative function, which we place into a variable (note we use <i>def</i> and not <i>defn</i>):
(def cubic-prime (derivative cubic))
We can now call the cubic-prime function simply like any other function:
The derivative of x^3 is 3 * x^2, which for an x of 4 equals 48. Our derivative is as precise as low is the value of the increment <i>dx</i>.
The above code translated from lisp code at [http://funcall.blogspot.com/2009/03/not-lisp-again.html funcall blog]. Thanks [http://www.blogger.com/profile/03233353484280456977 Joe Marshall] for sharing this perl.
← Older edit
Newer edit →
Retrieved from "
Set/change upload password