简体   繁体   中英

Errors in Composite Simpson's Rule in C++

I am writing a small program to approximate integrals in C++ using the composite Simpson's rule. It seems to work, but when I calculate the integral for different numbers of intervals (hence the for loop), some errors appear, as it seems completely at random. Here is my code.

#include <iostream>
#include <cmath>

double f(double x)
{
    double y = x;
    return y;
}

int main()
{
    for(double n=1; n<20; n+=1)
    {
        double a = 1;
        double b = 4;
        double d = (b-a)/n;
        double i = a;
        double area = 0;
        while(i<b)
        {
            double j = i + d;
            area += (d/6) * ( f(i) + 4*f((i+j)/2) + f(j) );
            i = i + d;
        }
        std::cout << "Order " << n << " : " << area << std::endl;
    }
    return 0;
}

The output is as follows.

Order 1 : 7.5
Order 2 : 7.5
Order 3 : 7.5
Order 4 : 7.5
Order 5 : 7.5
Order 6 : 7.5
Order 7 : 9.30612
Order 8 : 7.5
Order 9 : 7.5
Order 10 : 8.745
Order 11 : 8.6281
Order 12 : 7.5
Order 13 : 7.5
Order 14 : 7.5
Order 15 : 7.5
Order 16 : 7.5
Order 17 : 8.22145
Order 18 : 8.18056
Order 19 : 7.5

I think this might have something to with variable types or storing problems, although I can't figure out what the problem is. Any help is appreciated.

This is probably caused by floating point numbers comparison. 4.0<4.0 may be true in that case for the computer, making your loop go one time too many.

To solve the problem, you could use epsilon to compare numbers:

#define EPS 1e-8
if(a<b-EPS){...} // this is analogous to < operator for ints
if(a<b+EPS){...} // this is analogous to <= operator for ints

Another option is to generate your i variable on the fly, while using integers to control the loop:

for(int k=0;k<n;k++){
    double i=a+(b-a)*k/n;
    // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM