Skip to content

Instantly share code, notes, and snippets.

@divs1210
Last active August 1, 2020 11:01
Show Gist options
  • Save divs1210/4ca74577711eb996a89a36d86a38ea78 to your computer and use it in GitHub Desktop.
Save divs1210/4ca74577711eb996a89a36d86a38ea78 to your computer and use it in GitHub Desktop.
Calculus in Clojure
(ns calculus)
(defonce ^:const dx 0.00001M)
(defn df
"Returns the derivative of f."
[f]
(fn [x]
(/ (- (f (+ x dx)) (f x))
dx)))
(defn Sf*
"Definite integration of f over [a, b]
using Simpson's method."
[f a b]
(let [n (/ 1 dx)
h (/ (- b a) n)]
(loop [i 1
sum1 (f (+ a (/ h 2)))
sum2 0]
(if (< i n)
(recur (inc i)
(+ sum1
(f (+ a
(* h i)
(/ h 2))))
(+ sum2
(f (+ a (* h i)))))
(* (/ h 6)
(+ (f a)
(f b)
(* 4 sum1)
(* 2 sum2)))))))
(defn Sf
"Indefinite integral of f.
Returns a function that takes x and (optionally) c."
[f]
(fn this
([x]
(this x 0))
([x c]
(+ (Sf* f 0 x)
c))))
;; Usage
;; =====
(defn square [x]
(* x x))
(def twice (df square))
(def square-reborn (Sf twice))
;; Tests
;; =====
(defn almost=
"Checks if relative difference b/w x, y is < dx."
[x y]
(< (/ (Math/abs (double (- x y)))
x)
dx))
(if (and (almost= 3 (+ 3 dx))
(not (almost= 3 3.1))
;; differentiation
(almost= 6 (twice 3))
;; integration
(almost= 9 (square-reborn 3)))
(println "Tests passed!")
(println "Tests failed :("))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment