Skip to content

Instantly share code, notes, and snippets.

@calebsmith
Last active August 29, 2015 14:13
Show Gist options
  • Save calebsmith/89c6fe64e865704f5105 to your computer and use it in GitHub Desktop.
Save calebsmith/89c6fe64e865704f5105 to your computer and use it in GitHub Desktop.
Best fit using least-squares estimation in Scheme
(define (best-fit points)
;; Use least-squares estimation to find best fit line for given set of points
(let* ((sumx (apply + (map car points)))
(sumy (apply + (map cadr points)))
(sumxy (apply + (map (lambda (p) (* (car p) (cadr p))) points)))
(sumx2 (apply + (map (lambda (p) (* (car p) (car p))) points)))
(n (length points))
(slope (/ (- sumxy (/ (* sumx sumy) n)) (- sumx2 (/ (* sumx sumx) n))))
(y-int (/ (- sumy (* slope sumx)) n)))
(cons slope y-int)))
(define (best-fit_func points)
;; Given a set of points, use `best-fit` to a return the function for the
;; best fit line. (Can be called with a given x to return f(x) and used to
;; estimate further points)
(let* ((fx (best-fit points))
(slope (car fx))
(y-int (cdr fx)))
(lambda (x)
(+ (* slope x) y-int))))
;; Example run (> shows output)
;; --------------------------
(define points '(
(-4 -3)
(-3 -1)
(-2 -2)
(-1.5 -0.5)
(-0.5 1)
(1 0)
(2 1.5)
(3.5 1)
(4 2.5)
))
(display (best-fit points))
> (0.551931330472103 . -0.0248927038626609)
(map (lambda (e) (begin (display e) (newline))) (map (best-fit_func points) (iota 10)))
> -0.0248927038626609
> 0.527038626609442
> 1.07896995708154
> 1.63090128755365
> 2.18283261802575
> 2.73476394849785
> 3.28669527896996
> 3.83862660944206
> 4.39055793991416
> 4.94248927038627
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment