Search code examples
c++montecarlo

Monte carlo integration for area under curve


I have managed to code a program that uses the monte-carlo method to estimate pi. Now i am trying to instead estimate the area of plane curves, specifically a quadrifolium.See image for reference I have been unable to do this so far. Surely this only involves a tweak to my current code? Any help or advice would be appreciated. Here is what i already have:

#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;

Solution

  • First, I must precise that Monte Carlo is by far not the best method to solve this problem. This solution exploit the fact that for both x and y superior to 0, ((x^2+y^2)^3 < 4x^2y^2) => (x,y) belongs to the surface.

    #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;
        }