Created
March 26, 2010 14:08
-
-
Save farhaven/344919 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <math.h> | |
| #include <string.h> | |
| #define ENTROPY 1000 | |
| void usage(const char* name) | |
| { printf("Usage:\n"); | |
| printf("%s [xxxx] [-vh]\n", name); | |
| printf("xxxx\tuse xxxx random numbers to calculate pi, default 1000\n"); | |
| printf("-v\tshow progress\n"); | |
| printf("-h\tshow this message\n"); | |
| exit(1); | |
| } | |
| int main(int argc, char* argv[]) | |
| { srand(time(0)); | |
| long entropy = ENTROPY; | |
| char verbose = 0; | |
| while (argc-- > 1) | |
| { if (!strcmp(argv[argc], "-v")) | |
| verbose = 1; | |
| else if (!strcmp(argv[argc], "-h")) | |
| usage(argv[0]); | |
| else | |
| entropy = atoi(argv[argc]); | |
| } | |
| long hit = 0, total = 0; | |
| if (verbose) | |
| printf("Gathering entropy, please wait...\n"); | |
| for (; total != entropy - 1; total++) | |
| { long double x = (1.00 * rand()) / (RAND_MAX); | |
| long double y = (1.00 * rand()) / (RAND_MAX); | |
| if ((x*x) + (y*y) <= 1) hit++; | |
| if (verbose) | |
| printf("\r%.3f%% %ld (%ld) / %ld",((1.00 * total) / entropy) * (100.00), total,hit, entropy); | |
| } | |
| long double pi = ((1.00 * hit) / (1.00 * total + 1)) * 4; | |
| if (verbose) | |
| printf("\napprox. value of pi: %.50Lf\n",pi); | |
| else | |
| printf("%.50Lf\n",pi); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment