Created
October 23, 2013 22:52
-
-
Save LBijaminas/7128267 to your computer and use it in GitHub Desktop.
Simple function to approximate the value of pi.
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 <time.h> | |
| #include <stdlib.h> | |
| int main(void) { | |
| double x, y, i; // variables | |
| double N0 = 0, Ntot = 100000000; // numbers that the numbers in the range and total numbers | |
| double A; // area var | |
| srand(time(NULL)); // initialize the random seed | |
| for( i = 0; i < Ntot; i++){ | |
| /** | |
| Lets find how many random values will be within the radius | |
| of 1, so that we could approximate the value of pi | |
| */ | |
| x = rand() / (double)RAND_MAX; | |
| y = rand() / (double)RAND_MAX; | |
| if ((x*x + y*y) < 1) N0++; | |
| } | |
| // Area is approximately number in the range over total numbers | |
| A = (double)N0/(double)Ntot; | |
| // Since we checked only the area of the quarter of the circle, | |
| // we need to find the full circle by multiplying by four | |
| printf("Pi is %.30f\n", 4*A); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment