I implemented the golden section search algorithm recursively in Lisp. My code is:
(defconstant phi 0.618033988749895D0)
(defun linemin (f x1 x2 &key (xi1 (- x2 (* (- x2 x1) phi)))
(xi2 (+ x1 (* (- x2 x1) phi)))
(tol 0.001))
(if (> tol (- xi2 xi1))
(/ (+ xi1 xi2) 2)
(if (> (funcall f x1) (funcall f x2))
(linemin f xi1 x2 :tol tol :xi1 xi2)
(linemin f x1 xi2 :tol tol :xi2 xi1))))
I sought to make this tail-recursive. Does Lisp provide a way of ascertaining whether the function was optimized and turned into a loop at compile time? Btw I'm using Lispworks.
Any other input is appreciated, of course.
defvar
/defparameter
, otherwise the compiler is free to do about anything when you're redefining the constant) and they're also named+phi+
by convention. I guess though there's a point in thatpi
doesn't follow that convention. \$\endgroup\$defconstant
to prevent thephi
from being inadvertently changed by the formulae within the function. The*phi*
convention has pros and cons, but I agree it looks like a good idea. \$\endgroup\$