Nonlinear minimization in javascript
For certain experiments in psychology, especially those with tasks in which parameters are changed in response to the behavior of the subject ('adaptive testing'), it is useful to be able to minimize a function. DHTML is very useful for implementing such tasks (and an extemely cheap alternative for expensive experimentation software such as E-Prime), and so it is useful to have a javascript algorithm for function minimization. I found a useful C algorithm that was straightforward enough to translate into JavaScript (click the title of this post to download). It is an implementation of the Hooke and Jeeves algorithm (with improvements; read this for a conceptual explanation and comparison to other algorithms). Good things of this algorithm are: light weight and simple code, reasonably robust, multidimensional minimization, no gradients required, and open source. This javascript implementation is easy to use as the example below demonstrates:
The full documentation is provided in the source.
<script type=text/javascript src="hooke.js"><script/>
<script>
function g(x, n) // x contains the parameters, n is the # of params
{
c = -Math.exp(-(4-x[0])*(4-x[0])) + (x[1]*x[1]);
return (c);
}
var console = document.getElementById("console")
var a = new Hooke(g); // new minimizer object
a.startpt = [5, 1.9]; // starting point
a.setConsole(console); // give a div element for diagnostic output
a.main(); // start searching
var result = a.endpt; // array containing the coordinates found
<script>
<div id=console></div>
console
The full documentation is provided in the source.

1 Comments:
Just found your blog - incredibly helpful! Thank you!
Post a Comment
<< Home