-
Notifications
You must be signed in to change notification settings - Fork 18
/
pi.c
73 lines (62 loc) · 1.57 KB
/
pi.c
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
69
70
71
72
73
/*
* File: pi.c
* Author: Andy Sayler
* Project: CSCI 3753 Programming Assignment 3
* Create Date: 2012/03/07
* Modify Date: 2012/03/09
* Description:
* This file contains a simple program for statistically
* calculating pi.
*/
/* Local Includes */
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <errno.h>
/* Local Defines */
#define DEFAULT_ITERATIONS 1000000
#define RADIUS (RAND_MAX / 2)
/* Local Functions */
inline double dist(double x0, double y0, double x1, double y1){
return sqrt(pow((x1-x0),2) + pow((y1-y0),2));
}
inline double zeroDist(double x, double y){
return dist(0, 0, x, y);
}
int main(int argc, char* argv[]){
long i;
long iterations;
double x, y;
double inCircle = 0.0;
double inSquare = 0.0;
double pCircle = 0.0;
double piCalc = 0.0;
/* Process program arguments to select iterations */
/* Set default iterations if not supplied */
if(argc < 2){
iterations = DEFAULT_ITERATIONS;
}
/* Set iterations if supplied */
else{
iterations = atol(argv[1]);
if(iterations < 1){
fprintf(stderr, "Bad iterations value\n");
exit(EXIT_FAILURE);
}
}
/* Calculate pi using statistical methode across all iterations*/
for(i=0; i<iterations; i++){
x = (random() % (RADIUS * 2)) - RADIUS;
y = (random() % (RADIUS * 2)) - RADIUS;
if(zeroDist(x,y) < RADIUS){
inCircle++;
}
inSquare++;
}
/* Finish calculation */
pCircle = inCircle/inSquare;
piCalc = pCircle * 4.0;
/* Print result */
fprintf(stdout, "pi = %f\n", piCalc);
return 0;
}