sanjep
sanjep

Reputation: 65

Composite simpson rule code keep getting wrong output?

Algorthim:enter image description here

I am trying to implement this composite Simpson rule that will calculate the following integral: 1/sqrt(x) which should result in: 2

However, I keep getting the wrong output such as 1.61663

#include <cmath>
#include <iostream>
using namespace std;

double f(double n)
{

    return 1/sqrt(n);
}

double simpson(double a, double b, double n)
{

double x0=f(a)+f(b);
double h=(b-a)/(n);
double x1=0,x2=0;
double x=0;
for(int i = 1 ; i <n;i++){
        x=a+(i*h);
        if(i%2==0)
        {
            x2=x2+f(x);
        }
        else
        {
            x1=x1+f(x);
        }
    }
        x1=(h*(x0+2*x2+4*x1))/3;
        return x1;
}

 int main(){

            cout<<"Integral is: "<<" "<<simpson(0.0004,1,20)<<" "<<endl;
    }

Upvotes: 1

Views: 104

Answers (1)

Evg
Evg

Reputation: 26372

The problem is not in your code, but in the function you're trying to integrate. This function diverges to infinity as x goes to zero. The derivatives also diverge.

For the interval [a, 1] with small a, the error term is bounded by O[1/(N^4 a^4.5)]. That's why to calculate the integral over this interval, the grid should be very dense to get a reasonable error bound.

simpson(0.0004, 1, N) produces the following values:

N      Result         Error
--------------------------------
20     2.549041009    0.5890
200    1.986462457    0.0265
2000   1.960181808    1.8181e-4
20000  1.960000049    4.9374e-8 
200000 1.960000000    5.0810e-12

And indeed, for large N we are getting closer and closer to the exact value 1.96 with the error O(1/N^4).

Upvotes: 1

Related Questions