Skip to content

Instantly share code, notes, and snippets.

@divs1210 divs1210/calculus.clj
Last active Oct 26, 2018

Embed
What would you like to do?
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 less than 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
You can’t perform that action at this time.