This C code shows implementation of Monte carlo algorithm. And code is helpful while user is in between any algorithmic manipulation task.
code:
//Tested Ok on Code::Blocks IDE 17.12
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
int main()
{
int no_of_darts,i;
float x1=5.0,y1=5.0,x2,y2,radiussq,green_dart=0,gray_dart=0,pi;
time_t t;
srand((unsigned) time(&t));
printf("\nEnter the No Of Darts : ");
scanf("%d",&no_of_darts);
for(i=0; i<no_of_darts; i++)
{
//generating random float numbers between 0.0 to 10.0
x2=(float)(( rand()%65535)/65535.0f)*10;
y2=(float)(( rand()%65535)/65535.0f)*10;
//distance formula calculating square of radius
radiussq=((y2-y1)*(y2-y1)+(x2-x1)*(x2-x1));
if(radiussq<25.0f)
{
green_dart++;
}
else
{
gray_dart++;
}
}
pi=green_dart/no_of_darts*4;
printf(" \n\t Value of Pi=%f \n",pi);
getchar();//getc(stdin);
return(0);
}
//end of program
To see such C code reviews refer blog archieve at right side or click CCode lable for till posted posts list.
...till next post, bye-bye and take care.
No comments:
Post a Comment