Instantly share code, notes, and snippets.

# ericnormand/00 derivative.md

Last active Aug 9, 2019

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: 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 ([f] (deriv f 1e-5)) ([f h] #(/ (- (f (+ % h)) (f %)) h))) (comment (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 ([f] (deriv f default-h)) ([f h] (fn [x] (/ (- (f (+ x h)) (f x)) h)))) (defn square [x] (Math/pow x 2)) (def dsquare (deriv square))