I am trying to complete the task of integrating with the right rectangle rule, but I am stuck at one moment. The first two values are being outputted, but further ones are just 0... The task is about starting with iteration count 3 and continuing up to 512, by multiplying iteration count by 2 every time. I feel something is wrong here, but I can't see what. Let the test values be, as in the task: 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;
}
But values keep increasing drastically:
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
CodePudding user response:
- Change
sum = Function(lower pre_sum i);
tosum = Function(lower pre_sum * i);
. That is, you should multiply byi
rather than add it.i
represents the index of the iteration (indexed by 1 for right-rectangle integration; indexed by 0 for left-rectangle integration.) - Change
for (int i = 1, step ; i < iteration_count; i )
tofor (int i = 1; i <= iteration_count; i )
. That is, check for less-than-or-equal rather than less-than inequality. Otherwise, the number of iterations performed is actually one less thaniteration_count
, which is likely unintended behavior.step
was also removed, since it's dead code.
Output:
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