I have written a function that takes in a long long value n
and uses that as the number of iterations to go through. The function should give a good estimate of pi, however, all the values for large n
tends towards 3.000, and not 3.1415,so I am not sure what is going on?
Is there anything that I did wrong?
This is my code:
double estimate_pi(long long n){
double randomx, randomy, equation, pi;
long long i, incircle = 0;
for(i = 0; i < n; i++){
randomx = (double)(rand() % (1+1-0) + 0);
randomy = (double)(rand() % (1+1-0) + 0);
equation = randomx * randomx + randomy * randomy;
if(equation <= 1){
incircle++;
}
}
pi = (long double)4 * (long double)incircle / (long double)n;
return pi;
}
in the main function, to print 10 values of pi:
int main(void){
long long N;
double pi_approx;
int i;
printf("Input a value of N: ");
if(scanf("%ld", &N) != 1){
printf("Error, input must be an integer!\n");
exit(EXIT_SUCCESS);
}
if(N < 1){
printf("Error, the integer must be positive!\n");
exit(EXIT_SUCCESS);
}
srand(time(NULL));
for(i = 0; i < 10; i++){
pi_approx = estimate_pi(N);
printf("%.10f\n", pi_approx);
}
return 0;
}