Gradient ascent

Gradient Ascent


In this experiment I wanted to make a simple gradient ascent algorithm. For that, I used Three.js to display the graph of the function and the red particle that follows the algorithm.

To compute the gradient of the function I used Algebrite, a JavaScript library for symbolic computation. It’s good as a Computer Algebra System, but it’s a bit slow evaluating expressions, and having to evaluate the entered expression 360000 times to generate the graph wasn’t exactly instantaneous.

For that reason, I decided to turn the expressions into JS functions using new Function(), as computing those is much faster. This method is not safe, and shouldn’t be used for anything important! From MDN:

Calling the constructor directly can create functions dynamically but suffers from security and similar (but far less significant) performance issues to eval. However, unlike eval, the Function constructor creates functions that execute in the global scope only.

Despite the security concerns, I’m not really sure it’s an issue in this case, as entering any JS as an equation should make Algebrite throw an error, and would make the function not be created.

You can see more about how it works in the code below:

© 2020 Guillem Caballero Coll