Nameless King
Nameless King

Reputation: 65

Problems with finding π using Monte Carlo method in C++

I have a program that is supposed to find an approximate of π using the Monte Carlo method, and the code is as below:

#include <iostream>
#include <cstdlib>
#include <cmath>

int main()
{
    double x=0, y=0, piEstimate=0, precision=0;
    int N;
    int nIn=0, nOut=0;
    std::cout << "Please enter the seed number." <<std::endl;
    std::cin >> N;
    for(int i=0;i<=N;i++){
        x=(double)rand()/(double)RAND_MAX;
        y=(double)rand()/(double)RAND_MAX;
        if(sqrt(x*x+y*y)>1){
            nOut++;
        }else if(sqrt(x*x+y*y)<1){
            nIn++;
        }
    }
    piEstimate=4*(nOut/nIn);
    std::cout<<"The estimate of pi with "<<N<<" seeds is "<<4.0*(nOut/nIn)<<"."<<std::endl;
    std::cout<<"Error percentage at "<<abs(100.0-piEstimate/3.1415926)<<"."<<std::endl;
}

This, however, generates the following output, which seems unreasonable: montecarloprogramoutput What is the problem here, and why is the program generating such inaccurate numbers for π? I assume my logic fails somewhere in the middle, but I can't figure out where... Running in Code::Blocks 16, C++0X standards.

Upvotes: 1

Views: 2224

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122133

The area of the quarter circle is

inside = (pi*r^2)/4

area of the quarter square is

total = r^2

and the area of the "outside"

outside = total - inside = r^2 - (pi*r^2)/4

So you got the formula wrong. You need to compare the total trials and the trials inside, not outside/inside:

4* inside / total  = pi

Btw when doing monte carlo and asking for precision you should not use rand() but the facilities you can find in <random>.

Upvotes: 6

Related Questions