Created
January 27, 2012 14:12
-
-
Save hans/1688958 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns euler.utils.derivative | |
(:use clojure.contrib.math)) | |
(defn take-with-epsilon | |
"Take from a list of numbers xs until two numbers are within the epsilon eps. | |
Check a maximum of `limit` times. Returns the last number of the satisfying | |
pair or nil of no match is found." | |
[xs eps limit] | |
(let [next (rest xs)] | |
(loop [prev-x (first xs) x (first next) xs (rest next) i 0] | |
(if (or (= i limit) (nil? x)) | |
nil | |
(let [scaled-eps (if (or (zero? prev-x) (zero? x)) | |
eps | |
(* eps (abs x)))] | |
(if (<= (abs (- x prev-x)) scaled-eps) | |
x | |
(recur x (first xs) (rest xs) (inc i)))))))) | |
(defn n-derivative [f x] | |
(let [halve #(/ % 2) | |
h-slope #(/ (- (f (+ x %)) (f (- x %))) (* 2 %)) | |
hs (iterate halve 2)] | |
(take-with-epsilon (map h-slope hs) 0.00001 50))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment