Main question:
Can I use a variable in replace of a Math.
function that defines the math function at the end of the Math
object so Math.variableName
will be the same as Math.sin(x)
(if variableName = 'sin(x)'
)?
I'm creating a simple math graphing calculator in JavaScript. I have a variable that stores a user's equation:
var userEquation = $('#userEquation');
and for this case, let's say the user typed: sin(x)
.
I want to be able to use the Math.
object for any equation the user may put in, such as cos(x)
, or cos(x)/sin(x)
. This is the function that converts the user input to Math.userEquation
.
function getEquation(x) {
var userEquation = $('#userEquation').val(); // or pretty much "var userEquation = 'sin(x)'
return Math.equation;
}
The function returns undefined
, for there is no Math.userEquation
. What does work is:
return Math.sin(x);
But this won't work if the user types a more complicated formula that's not already specified in my program. Is there a way to use the Math
object with a variable?
EDIT: I did not want to use external libraries in this besides jQuery if at all possible. The other question similar to this one found here, used external libraries not directly built into JavaScript.
EDIT 2:
My graph function looks like this:
for (var i = iMin; i <= iMax; i++) {
xx = dx * i;
var formula = xx / scale;
yy = scale * getEquation (formula); // Should be Math.sin(xx/scale) for getEquation
if (i == iMin) ctx.moveTo(x +xx, y - yy);
else ctx.lineTo(x + xx, y - yy);
}
ctx.stroke();
This function uses the equation function in the for loop for ex in order to find the points to plot, and it didn't work with external libraries.
I don't think that Math.sin(x)*cos(x)
works as is on its own, will another method help solve this if it's in a variable as well?