the problem of for loop

My teacher asks let me design a program to find the area of the ellipse.We can not use the pi and any other libraries.
The precision and xy-axis are given.
The problem is when I enter the precision is 0.0001 and xy is 1 1, it works.Btw when I enter 0.0000001, it does not work.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
 #include <iomanip>
#include <iostream>
using namespace std;
#include <math.h>
double precision;
double  xaxis;
double  yaxis;
unsigned long long int squares=0;
double powa;
double powb;

main(){


cout << "Please enter the precision: " << endl;
cin >> precision;
cout << "Please enter the width and height of the ellipse: " << endl;
cin >> xaxis >> yaxis;
powa = pow(xaxis,2);
powb = pow(yaxis,2);

double i;
for (i= precision / 2;i < xaxis ;i = i + precision){
double j;
for( j = precision / 2;j <= yaxis ;j = j + precision){
	if(pow(i,2) / powa  + pow(j,2) / powb <= 1){
		 ++squares;
	}}}

long double area = 4.0*squares*precision*precision;
cout << setprecision(9) << area << endl;

    return 0;


}
Last edited on
What do you mean by "does not work"?

It's trying to work out whether 10^14 little squares are inside one quadrant of the ellipse - I mean, give the poor thing a bit of time!

I should just do numerical integration instead.
It didn't show results, I have waited 30 minutes.😂😂
https://course.cse.ust.hk/comp2011/labs/lab3/circle-example.png

In the above picture, by looking at whether the center of a small grid is within the circle or not, we have counted that 20 small squares should be considered for the area of the circle. Therefore, the estimated area of this circle is 4*20*0.2^2

this is the concept of my program.😢
I know what you are trying to do, but you've got too many squares (and you might run into floating-point round-off errors as well). 20 squares is fine. 100000000000000 squares is not.

Use numerical integration: trapezium rule, mid-ordinate rule or Simpson's rule.
Unfortunately, the teacher forbids us to use other methods.😫
I doubt that your teacher expected you to use such tiny squares.
My teacher just wants to fool me.😂
if you want high precision squares using this method you can probably break it down like a fractal, where you use a large square in the middle of the ellipse and as you move toward the edges you cut your squares into 4x so when you reach the edge you have a lot of them and in the middle you have <10 or so...

it will run a little faster if you change pow to x*x .. pow is notably slower for large numbers of calls.

also remove that if statement:
say this:
squares += (int)((i*i / powa + j*j / powb <= 1))


theres only so much you can wring out of brute force, though.
also, make SURE you COMPILE with MAX SPEED optimize ON.
Last edited on
Topic archived. No new replies allowed.