Skip to content
pi_shared.c 2.06 KiB
Newer Older
#include <stdlib.h> // rand_r, RAND_MAX, EXIT_FAILURE, atoi
#include <stdio.h> // printf
#include <time.h> // time

void read_arguments(int *seed, int *N, int argc, char *argv[]) {
    /*
     * parse command line arguments to obtain
     * - seed: seed for the pseudo random number generator
     * - N: number of random samples
     */

    // check if enough arguments are given
    if (argc != 3) { 
        // print usage information
        printf("USAGE %s <seed> <N>\n", argv[0]);
        printf("  seed (integer): seed for the pseudo random number generator\n");
        printf("                  a negative value indicates current timestamp\n");
        printf("  N (integer)   : number of random samples to use\n");
        // do not continue if number of arguments is invalid
        exit(EXIT_FAILURE);
    }

    // read seed for the pseudo random numnber generator
    // WARNING: according to the man page, atoi does not detect errors
    *seed = atoi(argv[1]);
    if (*seed < 0) {
        // use current timestamp as seed
        *seed = time(NULL);
    }

    // read number of random samples
    // WARNING: according to the man page, atoi does not detect errors
    *N = atoi(argv[2]);

}


int count_hits(unsigned int seed, int N) {
    // create N random ((double) x, (double) y) coordinates, where x:[-1, 1], y:[-1, 1]
    // return the number of coordinates falling inside a unit circle

    int i;
    double x;
    double y;
    int hits;

    // start with 0 hits
    hits = 0;

    // for N random samples
    for (i=0; i<N; i++) {

        // create a random 2D coordinate
        x = -1. + 2. * (double)rand_r(&seed) / (double)RAND_MAX ;
        y = -1. + 2. * (double)rand_r(&seed) / (double)RAND_MAX ;

        // if coordinate falls inside unit circle, increase hit counter
        // ISO C standard guarantees the return value of comparison operators
        // to be (int) 0 for false and (int) 1 for true results
        // therefore, we can avoid branching (i.e. if (...) hits++;)
        hits += ( (x*x + y*y) < 1. );

    }

    // return number of hits
    return hits;

}