C++ Integration Solution using Riemann Sum : Loses validity for greater than 10 partitions
In an effort to code the briefest solution I could for an approximation of the integral using Riemann sums, I ran into a strange problem: if the user requested a partition count in excess of 10, the program failed. Any thoughts? Here's the code:
// The Integral
#include <algorithm>
#include <iomanip>
#include <ios>
#include <iostream>
#include <stdexcept>
#include <iomanip>
using std::cin; using std::cout;
using std::endl;
int func (int x);
int main ()
{
cout << "Please enter left and right bounds: ";
int left, right;
cin >> left >> right;
cout << "Please enter a # of partitions (>0): ";
int R;
cin >> R;
int width = (right - left) / R;
int total = 0;
for (int i = 0; i < R; ++i) {
total += func(left + width*i);
}
cout << "The integral is: " << total << endl;
return 0;
}
int func (int x)
{
r开发者_开发知识库eturn x*x;
}
Using a partition size of greater than 10 is not your actual problem.
Your are using integers for your variables and function return value, when you should be using float
or double
.
For instance:
int width = (right - left) / R;
If (right - left) < R
width will be zero!
on a side note, unless you plan on expanding this small prog, you're including way to many useless stuff. this is all you'd need for this prog:
#include <iostream>
#include <cstdio>
using namespace std;
int func (int x)
{
return x*x;
}
int main()
{
// if you have your main() at the bottom, you dont have to declare other functions on top.
}
cheers :)
Another comment:
In my opinion the for-loop in your code does not compute the correct Riemann-sum. I think it should look like this:
for (int i = 0; i < R; i++) {
total += func(left) * width;
left += width;
}
Cheers :)
精彩评论