用直角矩形法则积分

2022-01-30 14:55:32 标签 c++math

我试着用矩形法则来完成积分的任务,但我有一次卡住了。前两个值正在被输出,但进一步的值只是0…

该任务从迭代计数3开始,通过每次将迭代计数乘以2,一直到512。

我觉得有点不对劲,但看不出来是什么。测试值如下:lower: -3 upper: 6 starting iteration count: 3

#include <iostream>
using namespace std;
double Function(double x)
{
    if (x < 0)
        return (1 / sqrt(25 + (3 * x)));
    else
        return pow(x, 2) + 0.2;
}
double Integrate(int upper, int lower, int iteration_count)
{
    double pre_sum = (double)((double)(upper - lower) / iteration_count);
    double sum = 0;
    for (int i = 1, step ; i < iteration_count; i++)
    {
        sum += Function(lower + pre_sum + i);
    }
    return sum * pre_sum;
}
int main()
{
    int upper, lower, iteration_count;
    cout << "Enter lower bound: ";
    cin >> lower;
    cout << "Enter upper bound: ";
    cin >> upper;
    cout << "Enter iteration count: ";
    cin >> iteration_count;
    for (int i = iteration_count; i < iteration_count * 512; i=i*2)
    {
        cout << "Integration result: " << Integrate(upper, lower, i) << endl;
    }
    return 0;
}

但价值在急剧上升:

Enter lower bound: -3
Enter upper bound: 6
Enter iteration count: 3
Integration result: 16.2
Integration result: 33.0094
Integration result: 198.962
Integration result: 1138.16
Integration result: 5578.55
Integration result: 24809.2
Integration result: 104733
Integration result: 430463
Integration result: 1.74547e+06

# # #改变sum += Function(lower + pre_sum + i); to sum += Function(lower + pre_sum * i);. Th. 应该乘以i rather than add it. ii represents the index表示迭代的索引(右矩形积分的索引为1;左矩形积分的索引为0。)

改变for (int i = 1 step ; i < iteration_count; i++) to for (int i = 1; i <= iteration_count; i++). Th. 这是检查小于或等于,而不是小于等于不平等。否则,执行的迭代次数实际上是小于1的iteration_count which is likely unintended behavior. step was also removed since it's dead code.这很可能是无意识的行为。step was also removed since it's dead code也被删除了,因为它是死代码。

输出:

Enter lower bound: -3
Enter upper bound: 6
Enter iteration count: 3
Integration result: 136.8
Integration result: 103.081
Integration result: 87.911
Integration result: 80.7481
Integration result: 77.2722
Integration result: 75.5606
Integration result: 74.7114
Integration result: 74.2885
Integration result: 74.0774
阅读全文

▼ 版权说明

相关文章也很精彩
推荐内容
更多标签
相关热门
全站排行
随便看看

错说 cuoshuo.com —— 程序员的报错记录

部分内容根据CC版权协议转载;网站内容仅供参考,生产环境使用务必查阅官方文档

辽ICP备19011660号-5

×

扫码关注公众号:职场神器
发送: 1
获取永久解锁本站全部文章的验证码