Skip to content

Instantly share code, notes, and snippets.

@Jacajack
Created May 25, 2016 14:20
Show Gist options
  • Save Jacajack/1203fe3f662ba335361a1d474f4f22a9 to your computer and use it in GitHub Desktop.
Save Jacajack/1203fe3f662ba335361a1d474f4f22a9 to your computer and use it in GitHub Desktop.
Simple code calculating Pi with Monte Carlo method (this time in shape of square)
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#define SQ(x) ((x)*(x))
#define DIA 200.0L
int main( ){uintmax_t step = 0,
cir= 0; double x, y;long double
pi; while ( 1 ) { x = ( double)
rand()/RAND_MAX*DIA- DIA / 2.0;
y = (double)rand() / RAND_MAX *
DIA - DIA / 2.0;cir += ( SQ(x)+
SQ( y ) < SQ( DIA / 2.0 ) )? 1:
0;step++;pi=cir / (long double)
step * SQ( DIA );pi=pi /SQ( DIA
/ 2.0L ); if (step %(uint32_t)
1.0e6 == 0)printf("\r%.40Lf - "
"step %e", pi, (double)step);}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment