Skip to content

Instantly share code, notes, and snippets.

@MitchCarroll
Last active December 19, 2015 06:09
Show Gist options
  • Save MitchCarroll/5909683 to your computer and use it in GitHub Desktop.
Save MitchCarroll/5909683 to your computer and use it in GitHub Desktop.
Non-deterministic conic fitting. runs something like 320,000,000 iterations to determine a conic section which fits a set of data points.
;; The following definition for amb, assert and other operators are from Teach Yourself Scheme in Fixnum Days by Dorai Sitaram.
(define amb-fail '())
(define initialize-amb-fail
(lambda ()
(set! amb-fail
(lambda ()
(error "amb tree exhausted")))))
(initialize-amb-fail)
(define-macro amb
(lambda alts
`(let ((+prev-amb-fail amb-fail))
(call/cc
(lambda (+sk)
,@(map (lambda (alt)
`(call/cc
(lambda (+fk)
(set! amb-fail
(lambda ()
(set! amb-fail +prev-amb-fail)
(+fk 'fail)))
(+sk ,alt))))
alts)
(+prev-amb-fail))))))
(define assert
(lambda (pred)
(if (not pred) (amb))))
(let ((a (amb -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0
1 2 3 4 5 6 7 8 9 10))
(b (amb -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0
1 2 3 4 5 6 7 8 9 10))
(c (amb -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0
1 2 3 4 5 6 7 8 9 10))
(d (amb -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0
1 2 3 4 5 6 7 8 9 10))
(e (amb -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0
1 2 3 4 5 6 7 8 9 10))
(f (amb -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0
1 2 3 4 5 6 7 8 9 10))
(conic (lambda (x y a b c d e f)
(+
(* a (expt x 2))
(* b x y)
(* c (expt y 2))
(* d x)
(* e y)
f))))
(assert (= 0 (conic -2 4 a b c d e f)))
(assert (= 0 (conic -1 1 a b c d e f)))
(assert (= 0 (conic 0 0 a b c d e f)))
(assert (= 0 (conic 1 1 a b c d e f)))
(assert (= 0 (conic 2 4 a b c d e f)))
(list a b c d e f)) ;; ax^2 + bxy + cy^2 + dx + ey + f = 0
@MitchCarroll
Copy link
Author

I used code for the amb operator and such from Teach Yourself Scheme in Fixnum Days by Dorai Sitaram.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment