I am trying to make a method that takes a string formula, and solves the integral of that formula by doing a Riemann\'s sum with very small intervals. I am using the ScriptE
Your JS snippet returns an Integer
(*), because x^2
is not the correct way to get a power of 2 in JavaScript. Try 5*Math.pow(x,2)
instead, and the expression will return a Double
.
In JavaScript, ^
operator is bitwise XOR.
Also the loop to compute the integral is wrong, you need to multiply by rectangle width:
double delta = 0.001;
for (double i = lower; i < upper; i += delta) {
//evaluates the interval
engine.put("x", i);
total += delta * ((Number) engine.eval(function)).doubleValue();
}
(*) See David's answer for a tentative explanation. But in comments, @A.Sundararajan provides evidence against this. I have not investigated the exact reason, I have only observed I got an Integer
, and was only guessing the use of bitwise operation in expression (from OP's original code) was triggering a conversion to integer. I originally edited my post to include the fix for "math error", but David's newer answer (by about 4 minutes ^^) is more complete for the original question, and should remain the accepted answer IMHO.