C++ Riemann Sum Problem

Hello,

The code below is supposed to calculate the area under the curve. I managed to get the code to work by setting delta to 1 or even smaller numbers like 0.25 and 0.50. However, when I make the size of delta even smaller, the program will take forever to run. Any ideas?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
using namespace std;

double f(double x) {
   return x * x;
}

double area(int a, int b) {
   double delta = 0.5;
   double x = a;
   double riemannSum;
   while(x != b) {
      riemannSum += delta * f(x);
      x += delta;
   }
   return riemannSum;
}

int main() {
    cout << area(3, 5) << endl;
    cout << area(3, 7) << endl;
}
while (x < b)
which begs a general point: you don't usually want to compare doubles for equality or inequality. You can look up walls of text as to what happens, why it happens, and what to do when you get a chance.
Last edited on
Topic archived. No new replies allowed.