我试着用矩形法则来完成积分的任务,但我有一次卡住了。前两个值正在被输出,但进一步的值只是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 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