PLEASE HELP A COMP SCI MAJOR STUDENT OUT!!!!! (this is due in about 13 hours)
I need to Approximate the area of a quarter circle by using 10,000 rectangles.
I know I need to use riemann sum and I have tried adjusting this but I keep getting nan or some ridiculously high number. Ultimate test to see if this works is when I plug in a radius of 2 I should get pi. Please send help, it is desperately needed!
Thank you
#include <iostream>
#include <cmath>
using namespace std;
int main(){
int n=10000;
int r;
double x=r/n;
cout<<"Enter a radius for the circle: ";
cin>>r;
double area=0;
for(int i=1; i<=n; i+=1){
area += ((i*r)/n)*(sqrt((r*r)-((i*x)*(i*x))));
}
cout<<"The area of a circle with radius "<<r<<" is "<<area<<".";
return 0;
}
r should be a double.
You can't work out x until AFTER you input r.
The widths of your rectangles are wrong - they should be constant (r/n) - and the abscissas are also biased to end of interval.
Use code tags.
Don't double post.
Should take you about 2 minutes to fix that, not 13 hours.
He/she is (badly) numerically integrating the area under a quarter-circle x^{2}+y^{2}=r^{2}, or rearranged as
y=sqrt(r^{2}-x^{2})
So, it should be a sum of rectangle areas: width (r/n) times height (sqrt(r^{2}-x^{2})). (His/her x doesn't mean the same as mine. Under the square root, x=i*r/n is sort of OK, but is biased always to the end of the interval and in this instance where the height is decreasing will tend to give a slightly low answer.)
The area would then be (pi.r^{2}/4), giving pi if r is 2.
Numerical integration is considerably more efficient than Monte Carlo.
#include <iostream>
#include <cmath>
usingnamespace std;
int
main()
{
int n = 10000;
double r;
cout << "Enter a radius for the circle: ";
cin >> r;
double dx = r / n; // the width of each rectangle
double area = 0;
for (int i = 1; i <= n; ++i) {
double x = ???; // Put in the formula for x at the right side of the rectangle
double y = ???; // Put in the formula for the the value of y at x.
area += dx * y;
}
cout << "The area of a circle with radius " << r << " is " << area << ".";
return 0;
}
Here's what I get when I put in the correct(?) formulas:
Enter a radius for the circle: 2
The area of a circle with radius 2 is 3.14139.
thank you everyone for your help, please forgive my obvious errors I am new to coding. I really appreciate all the help and I was definitely able to finish on time! Thank you all again.