I ran into a little bit of a problem regarding the speed of a program, and I wondered how to solve it. I’m accepting a user input equation in the form of:
"y = 3*x^2 - 2*x"
For brevity, I will work with this example. After converting it into postfix, I get:
[ 3, x, 2, ^, *, 2, x, *, - ]
So then if I wanted to graph this, I just simply make an array of x values and find the corresponding y values for my line to pass through. However, the function will evaluate much more quickly (which is crucial to make animated graphics), if I could take this user input and turn it into a function such as:
function userExpression( x ){
return 3*Math.pow(x,2)-2*x
}
Is there any way to convert this string into a function for faster evaluation. I am well aware of the fact that I can just parse the postfix expression I’ve made and It will work, but I’m fairly sure this is going to become a pretty bad bottleneck, especially if I’m working with a 3D graph.
I had the idea to inject html with a script
tag into the page, but I’d like to hear what others would do in this situation. Also, I’d be interested to hear how you’d do it in other languages such as C or C++, Python, anything really.
If you have already figured out how to parse the expression and generate the requisite Javascript as a string, then you can optimize performance by creating a compiled function using the Function
constructor:
var expression = "return 3 * Math.pow(x, 2) - 2 * x;";
var func = new Function("x", expression);
snippet.log(func(-2));
snippet.log(func(-1));
snippet.log(func(0));
snippet.log(func(1));
snippet.log(func(2));
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Bear in mind the all usual caveats regarding eval()
because this really isn't all that different, though it should be more performant than eval()
because the function is compiled in the global scope.