Monte carlo 曲线下面积积分

Monte carlo integration for area under curve

我已经设法编写了一个使用蒙特卡洛方法来估计圆周率的程序。现在我正在尝试估计平面曲线的面积,特别是四叶草。See image for reference 到目前为止,我一直无法做到这一点。当然这只涉及对我当前代码的调整?任何帮助或建议将不胜感激。这是我已有的:

#include <math.h>
#include <ctime>
#include <xmemory>
using namespace std;
double pi_(double accuracy)
{
int n = 0, d = 0;
double x, y, latest_pi = 0;
double Origin_dist = 0;
do
{
    x = 0;
    y = 0;
    x = rand() % 100;
    y = rand() % 100;
    Origin_dist = sqrt(x * x + y * y);
    if (Origin_dist < 100.0)
    {
        d++;
        n++;
    }
    else
    {
        n++;
    }
    latest_pi = 4.0 * (d + 1.0) / (n + 1.0);
} while ((d < 3100) || (4.0 / (n + 1.0) < accuracy));
return latest_pi;
}
int main()
{
double accuracy;
srand((int)time(0));
cout << "Enter the accuracy: \n";
cin >> accuracy;
cout << pi_(accuracy) << endl;

首先,我必须明确指出 Monte Carlo 到目前为止并不是解决这个问题的最佳方法。这个解决方案利用了这样一个事实,即对于 x 和 y 都优于 0,((x^2+y^2)^3 < 4x^2y^2) => (x ,y) 属于曲面。

#include <math.h>
#include <ctime>
#include <iostream>

double pow(double x, int n){
    double r=1.0;
    for (int i=0; i<n; i++){
        r=r*x;
        }
    return x;
    }

bool belongTo_quadrifolium(double x, double y){
    return pow(pow(x,2) + pow(y,2), 3) - 4 * (pow(x, 2) * pow(y, 2)) < 0; 
    }



double montecarlo(double accuracy){
    unsigned int n = 0, d = 0;
    double x, y;
    do
    {
        x = 1.0*rand() / (RAND_MAX-1);
        y = 1.0*rand() / (RAND_MAX-1);
        if (belongTo_quadrifolium(x, y)){
            d++;
            n++;
            }
        else{
            n++;
            }
        } while (d < 3100|| (1.0/n > accuracy));
    return 4.0*d/n;
    }

int main(){
    double accuracy;
    srand((int)time(0));
    std::cout << "Enter the accuracy: \n";
    std::cin >> accuracy;
    std::cout << montecarlo(accuracy) << std::endl;
    return 0;
    }