我是想要找一個橢圓的面積 但不能用pi
precision我想要的準確率 當我輸入0.0001 它能顯示答案 但0.0000001時等多一個多小時也沒結果..
在上圖中,通過查看小網格的中心是否在圓內,我們算出應該為圓的面積考慮20個小正方形。 因此,該圓的估計面積為4 * 20 * 0.2 ^ 2 , 這是我的思路。
查看小網格的中心是否在圓內是利用了這個公式
#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;
}
就式論式
試試看
#include <iostream>
#include <math.h>
using namespace std;
double precision;
double xaxis;
double yaxis;
unsigned long long int squares=0;
unsigned long long int loopcnt=0;
double powa;
double powb;
double divi;
int 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, j;
for (i= precision / 2;i < xaxis ;i = i + precision){
divi = pow(i,2) / powa;
for( j = precision / 2;j <= yaxis ;j = j + precision) {
loopcnt++;
if ((divi + (pow(j,2) / powb)) <= 1){
++squares;
}
else {
break;
}
}
}
long double area = 4.0*squares*precision*precision;
cout << "xaxis:" << xaxis << " yaxis:" << yaxis << " precision:" << precision << " area:" << area << endl;
cout << "Loopcnt:" << loopcnt << " squares:" << squares << " ratio:" << (double)squares/loopcnt << endl;
return 0;
}
如果過得去的話
再來計較細節
換個思路,可以用矩形面積來逼近,這樣複雜度會降到O(n)。
我用javascript寫,不過意思一樣。第一個是你的解法,第二個是用矩形逼近:
//let preci = 0.00000001
let preci = 0.0001;
let a = 5;
let b = 3;
let sq = 0;
for(let y=0; y<b; y+=preci) {
for(let x=0; x<a; x+=preci) {
if(Math.pow(y,2)/Math.pow(b,2)+Math.pow(x,2)/Math.pow(a,2) <= 1) {
sq++;
}
}
}
console.log(4 * sq * Math.pow(preci,2));
sq = 0;
for(x=0; x<a; x+=preci) {
// x^2/a^2+y^2/b^2=1
// y^2=(1-x^2/a^2)*b^2
// y=sqrt((1-x^2/a^2)*b^2)
let y = Math.sqrt((1-Math.pow(x,2)/Math.pow(a,2))*Math.pow(b,2));
sq += y * preci;
}
console.log(sq*4);