dimanche 23 octobre 2016

Monte Carlo code in C , finding Pi with srand(seed)

I need to calculate the value of pi given the equation. pi = probability of being inside the circle * 4. probability of being inside the circle = number of points in the circle / number of points picked. Which are generated by rand() and srand(seed) to get consistenI don't know what is wrong with my code. It's supposed to be right but it's not giving the right output.

/*
the probability of being inside the circle
*/

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

double randomNumber(double lowerBound, double upperBound, int seed){
    return lowerBound +((double)rand()) / (((double)RAND_MAX)/(upperBound-lowerBound));
}

double generateRandom(int seed, int iterations){
    int count = 0;

    int inside=0;
    double X_value;
    double Y_value;


    while(count <=iterations){

        X_value = randomNumber(-1, 1, seed);
        Y_value = randomNumber(-1, 1, seed);

        if(X_value * X_value + Y_value * Y_value <= 1){
        inside+=1;
        }

        count++;
    }
    return inside;

}
void userInput(){

    int seed=0.0;
    int iterations=0.0;
    double valueOfPI=0.0;
    double inside=0.0;

    printf("Enter the seed for the random number generator: ");
    scanf("%d", &seed);
    srand(seed);

    printf("Enter the number of iterations to run: ");
    scanf("%d", &iterations);

    inside = generateRandom(seed, iterations);

    valueOfPI = 4*(inside / iterations);

    printf("The value of pi is %.5lf.\n", valueOfPI);
}

int main(){
    userInput();
}




Aucun commentaire:

Enregistrer un commentaire