Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#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;
}