I made this code to compute definite integrals in Processing. It works by getting the rectangle between the maximum value between the previous function value and the current function value, and then I calculate the area by multiplying the maximum value described before and the step. And finally, the integral is just summing all the areas.
I will do a version based on trapezoids, but that could get really slow because I would need to use the square root function witch is computationally intensive to compute.
Any suggestions are welcome.
float step = 0.0001;
int iterations = 0;
// y = x
float f1(float x) {
return 2 * x;
}
float integral(int a, int b) {
float sum = 0.0;
float prevI = a;
for (float i = a; i < b; i += step) {
float h = max(f1(prevI), f1(i));
sum += step * h;
prevI = i;
iterations++;
}
return sum;
}
void setup() {
println(integral(0, 1));
println(iterations);
}
the square root function witch is computationally intensive to compute
indeed? What platform/computing device? \$\endgroup\$