Skip to content

Instantly share code, notes, and snippets.

@cocontusfine
Created February 20, 2009 07:12
Show Gist options
  • Save cocontusfine/67357 to your computer and use it in GitHub Desktop.
Save cocontusfine/67357 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#define MAX_NUM 999999999
typedef struct{
long double ax;
long double ay;
}position;
int get_random(int min, int max){
return min + (int)(rand()*(max-min+1.0)/(1.0+RAND_MAX));
}
/* 任意の点の座標をランダムに取得 */
void get_position(position *pos){
pos->ax = get_random(0,100000000)/1000000;
pos->ay = get_random(0,100000000)/1000000;
}
/* 任意の点の座標を表示 */
void print_position(position pos){
printf("(%.1f,%.1f)\n", pos.ax, pos.ay);
}
/* 任意の二点間の距離を出す */
long double dist_pos(position pos1, position pos2){
long double diffx = pos1.ax - pos2.ax;
long double diffy = pos1.ay - pos2.ay;
return sqrt(diffx * diffx + diffy * diffy);
}
/* 半径50の円の領域内に入っているのかどうかを判定 */
int circle_include_judge(position pos){
position cir = {50.0, 50.0};
return 50.0 >= dist_pos(cir, pos);
}
/* πを出す */
double cal_pi(long double n1,long double n2){
return ((long double)4 * n1) / (n1 + n2);
}
/* main関数ですよ */
int main(void){
int i;
position point={};
long double n1,n2;
n1=n2=0;
srand((unsigned int)time(NULL));
for(i=0;i<MAX_NUM;i++){
get_position(&point);
if( circle_include_judge(point)){
n1++;
}else{
n2++;
}
}
printf("%f\n",cal_pi(n1,n2));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment