I wrote this to calculate pi by choosing a random point for x and y and checking to see if it is inside or outside of a unit circle, but i ran into a problem which i cant find out why. N is a number like 10, 100,1000 which is the number of points it trys to see is in the circle.
then if it is inside of the circle, it increments "inside" and then inside is divided by the number of N to get teh ratio, which should get closer to 3.1415.
Im not getting any values, and im not sure if that way i wrote it, if i will get a new random number for each loop of the while loop I am new to C, im trying to learn it after Java.
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> void initrand(void) { srand(time(0)); } float randfloat(void) { return rand()/(float)RAND_MAX; } int main(void) { int n = 10; float x; float y; float pi = 3.1415; float rootxy; initrand(); int z = 0; int inside = 0; x = randfloat(); y = randfloat(); float area = 0.25 * pi; float calculatedpi; rootxy = sqrt(pow(x,2) + (pow(y,2))); while (z < n){ if (rootxy > area) { inside++; z++; } else{ return 0; } calculatedpi = (inside/n); printf("%f", calculatedpi); } //printf("%f", calculatedpi); } Here is my revised loop when i debug it, it seems to work, all the way up to the calcutedpi part, it prints out 0.00000 and does not grab the values from inside the loop.
while (z < n){ x = randfloat(); y = randfloat(); rootxy = sqrt(pow(x,2) + (pow(y,2))); if (rootxy < area) { inside++; } else{ } z++; } calculatedpi = (inside/n); printf("%f", calculatedpi); }
float pi = 3.1415;in a program that tries to "guess" PI is kinda strange. Also, that value is somewhat bad. TryM_PIif you have a POSIX implementation (or2 * asin(1)).doublein the absence of a strong reason otherwise.