简体   繁体   English

C ++中的复合辛普森规则中的错误

[英]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. 我正在编写一个使用复合Simpson规则在C ++中近似积分的小程序。 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. 似乎可行,但是当我为不同数量的间隔计算积分时(因此for循环),出现了一些错误,因为它似乎是完全随机的。 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. 在这种情况下,对于计算机而言, 4.0<4.0可能是正确的,这会使循环进行一次太多。

To solve the problem, you could use epsilon to compare numbers: 要解决此问题,可以使用epsilon比较数字:

#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: 另一种选择是在使用整数控制循环的同时即时生成i变量:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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