Skip to content

Instantly share code, notes, and snippets.

What would you like to do?

Derivative of a function

In Calculus class, I learned two forms for the derivative. The first was the Limit definition. The other was a symbolic method, which used many identities that you had to learn to be able to find the derivative.

Here is the limit definition of the derivative:

Limit Definition of Derivative

For this challenge, define a function deriv that takes a function and returns the derivative of that function, using the limit definition. You can use any very small value for h, or perhaps provide it as an optional argument.

This exercise is taken from SICP Chapter 1, Section 3.4.

(defn deriv
(deriv f 1e-5))
([f h]
#(/ (- (f (+ % h)) (f %)) h)))
(require '[clojure.spec.alpha :as s])
(require '[clojure.spec.test.alpha :as stest])
(require '[expound.alpha :as expound])
(s/def ::number-fn (s/fspec :args (s/cat :n number?)
:ret number?))
(s/def ::h (s/and (s/double-in :min 0.0 :max 1.0 :NaN? false)
#(< 0.0 %)))
(s/fdef deriv
:args (s/cat :f ::number-fn
:h (s/? ::h))
:ret ::number-fn)
(stest/instrument `deriv)
(set! s/*explain-out* expound/printer)
(expound/explain-results (stest/check `deriv))
((deriv #(Math/pow % 2)) 4))
(def default-h 1e-6)
(defn deriv
(deriv f default-h))
([f h]
(fn [x]
(/ (- (f (+ x h))
(f x))
(defn square [x]
(Math/pow x 2))
(def dsquare (deriv square))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.