rapsoulCecil - 1 year ago 89
C++ Question

# Why I always get 2.8284 when estimating Pi using PRNGs?

I'm new to C++. I'm trying to statistically determine the value of Pi based on Ernesto Cesaro's Theorem using the computer system's random number generator. But what I have done now can input a seed number and generate 100 pseudo random numbers and then estimate the value of pi. The generator can generate different group of Pseudo random numbers. However the confusion is I always get the estimate of pi for 2.8284 with no change. Here is the code:

``````#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int seed;
cout << "input a seed number: " << endl;
cin >> seed;
srand(seed);
int i, a[100];
for (i = 0; i < 100; i++)
a[i] = rand() % 100 + 1;
cout << "The generated random numbers are: " << endl;
for (i = 0; i < 100; i++)
cout << a[i] << "\t";
int m, n, j, r;
int  sum = 0;
for (j = 0; j < 100; j++)
{
m = a[j];
n = a[j + 1];
j = j + 2;
do
{
r = m%n;
m = n;
n = r;
} while (r != 0);
if (n = 1)
sum = sum + 1;
}
double Pi, p;
p = 300 / sum;
Pi = sqrt(p);
cout << "The estimate value of Pi is: " << Pi << endl;
system("pause");
return 0;
}
``````

Note that Cesaro's theorem states that given two random integers, x and y, the probability that gcd(x, y) = 1 is 6/(Pi^2). And PRNG used affects how close the resulting estimate is to Pi(3.1416).

There are several issues with your code.

Issue #1:

``````if (n = 1)
``````

It should be `if (n == 1)` or else you are assigning `1` to `n` and always evaluating to true.

Issue #2:

``````      n = r;
} while (r != 0);
if (n == 1)
``````

If you think about it, the loop will end only when `r` is `0`, but then `n` will also be `0` because of the last line of the loop. So `n` will never be equal to `1`. You probably want `if (m == 1)`.

Issue #3:

``````for (j = 0; j < 100; j++)
{
...
j = j + 2;
``````

You are incrementing the `j` in the `for` line and in the loop body. You just need one.

``````for (j = 0; j < 100; j += 2)
{
//no j increment
``````

Issue #4:

``````p = 300 / sum;
``````

That is an integer division, because both numbers are integers. You want foating point: `p = 300.0 / sum;`.

With those changes I'm getting about `3.16`.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download