实现圆形区域的黎曼和

时间:2016-02-26 04:09:16

标签: c++

以下代码旨在实现此公式:

area=∑_(i=1)^n = w*√(r^2-(w×(i-1/2))^2 )

void integrate ( double R , double E )          //radius and acceptable error, entered by user
{
    int i = 1;                          //iterator
    int n = 1;                          //number of rectangles
    double x = 0;
    double width = 0;                   //stores width of each rectangle
    double area = 0;                    //stores calculated area
    double error = E + 1;               //stores difference between calculated area and pi*(radius)^2

    while ( error > E )                 //loop continues as long as error is greater than the acceptable limit entered by user
    {
        width = R / n;                  //sets the width of rectangles
        area = 0;                       //with this line, calculated area converges to zero. without it, calculated area increases without bound
        while ( i <= n )
        {
            x = i;                      //assign iterator value to a separate variable to avoid data type issues in calculation
            area += width * sqrt ( pow ( R , 2.0 ) - pow ( width * ( x - 0.5 ) , 2.0 ) );       //riemann integral formula
            i++;
        }
        n++;                                                    //increase number of rectangles by 1 to be used in next loop
        area *= 4;                                              //forumla uses one quarter of a circle, multiply by 4 to get total area
        error = abs ( area - ( pi * pow ( R , 2.0 ) ) );        //error calculation
        cout << " \n Calculated area = " << area << "\n"        //debugging output
             << " \n Error = " << error << "\n";
             cin.get();
    }
    cout << "\n Area: " << area << "\n"                         //output to user
         << "\n Error: " << error << "\n"
         << "\n Iterations: " << i << "\n";

    return;
}

正如评论所说,当行&#34; area = 0;&#34;包含在第一个循环中,该区域收敛到零,当它被移除时,该区域无限制地增加。我已经在一周的大部分时间里都在努力完成这一功能而没有任何进展。该程序的其余部分已完成,测试,并且工作正常。我不得不假设逻辑中的错误或我无法看到的数学错误。任何帮助将不胜感激。

我希望评论足够。我会在必要时提供额外的说明。

(这是一个独立的功能。除了用户输入之外,程序的其他任何部分都不会影响它或受其影响。)

0 个答案:

没有答案