How to get the value of each integral independently in c++?

Viewed 41

I am using simpson's 1/3 rule in c++ to find the integral of k*(x*x), where k=2*m and 'm' goes from 1 to 10, hence I have 10 integrals. When I wrote the code below I got the answers but its adding the values of integral from the previous ones! e.g. for m=1 => k=2 the integral is 0.66667, now for m=2 => k=4 instead of getting 0.33333, the integral is 2.00 (0.66667+0.33333). How to prevent it from doing that?

#include<iostream>
#include<cmath>
#include<iomanip>

using namespace std;

int k;
double f(double x) {
  return k * pow(x, 2);
}
int main() {
  int n = 100000, m;
  double h, a = 0, b = 1, sum = 0, x, y;
  cout << "The number of sub-intervals is n = " << n << endl;
  cout << fixed << showpoint << setprecision(5);
  for (m = 1; m <= 10; m++) {
    cout << "m = " << m << endl;
    k = 2 * m;
    cout << "k = " << k << endl;
    h = (b - a) / n;
    for (int i = 1; i <= n; i++) {
      x = a + i * h;
      if (i % 2 == 0) {
        sum = sum + 2 * f(x);
     } else {
        sum = sum + 4 * f(x);
      }
    }
    y = h / 3.0 * (f(a) + sum + f(b));
    cout << "The integration is: " << y << endl;
  }
}
0 Answers
Related