Simple definite integral calculator 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 &lt; 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);
}
Using the max of two consecutive values is asymmetric.
(I'd simply use the value sampled, avoids the following issue, too:)
For most every "sample" (i), the code computes the value of f() twice (f(prevI)): keep prevF instead  
a double (64 bits in Processing, as in Java) may be a saner type designator than float (32 bits),
especially for "the accumulator" sum.  When the number of summands approaches the number representable by its mantissa, you need a more sophisticated strategy than adding in numbers one by one.
the code multiplies each and every h by step:
don't, instead, multiply sum by step after the loop
(similarly, don't count trips/iterations, compute as (b-a)/step)
consider making step a parameter
(My pet idea would be setting a time limit and adding samples until time is up.
Depending on sampling strategy, keeping track of weights (width of the trapezoids, step) is a challenge.)