Loading web-font TeX/Main/Regular

Estimating Pi Using Monte Carlo Method [C, gnuplot]

Wednesday, October 10, 2018

C-language gnuplot Mersenne Twister Monte Carlo YouTube

t f B! P L
 

Make DAT file using Mersenne Twister [C]

Get "mt19937ar.h" → Mersenne Twister with improved initialization (2002)

monte_mt.c

  1. #include <stdio.h>
  2. #include <math.h>
  3. #include <string.h>
  4. #include "mt19937ar.h"
  5. #define N 1000000 // digit
  6.  
  7. int main(void){
  8. FILE *fp;
  9. double x, y;
  10. int z;
  11. int i;
  12. int cnt = 0;
  13. init_genrand(4234);
  14. fp = fopen("data.dat", "w+");
  15. for(i=1; i<=N; i++){
  16. x = (float)genrand_real1();
  17. y = (float)genrand_real1();
  18. if(x*x+y*y<=1){
  19. z = 1; //in
  20. cnt++;
  21. } else {
  22. z = 0; //out
  23. }
  24. fprintf(fp, "%.6f\t%.6f\t%1d\t%7d\n",x, y, z, cnt);
  25. }
  26.  
  27. fclose(fp);
  28. return 0;
  29. }
→make data.dat

Draw Monte Carlo method [gnuplot]

montecarlo.plt

  1. # Setting --------------------
  2. reset
  3. set terminal gif animate delay 6 enhanced size 1280, 720
  4. set output "montecarlo.gif"
  5. set nokey
  6. set size ratio 1
  7. set margins 0, 0, 0, 0
  8. set origin 0., 0.05 #0. = 0.0 (float)
  9. set size 0.9, 0.9
  10.  
  11. # Parameter --------------------
  12. N = 1e6
  13. cnt = 0
  14. png = 0
  15.  
  16. # Function (Label) --------------------
  17. Counter(i) = sprintf("%-8d", i)
  18. Approx(cnt, i) = sprintf("%-1.6f", 4.*cnt/i) #4. = 4.0 (float)
  19.  
  20. # Plot --------------------
  21. # Draw gray circle
  22. set object 1 circle at 0, 0 size 1 fc rgb 'gray80' fs transparent solid 0.15 noborder
  23. do for [j=1:820]{
  24. if(j<=100){
  25. i = j
  26. } else {
  27. k = j-100
  28. i = 10**((k-1)/180+2) + 5*((k-1)%180+1)*10**((k-1)/180)
  29. }
  30. # Set range for using stats command
  31. set xrange [0:i]
  32. set yrange [0:i]
  33. stats 'data.dat' using 4 every ::(i-1)::(i-1) nooutput
  34. cnt = STATS_max
  35. # Displey labels
  36. set label 1 "N = ".Counter(i) left at screen 0.75, 0.56 font 'Times New Roman:Normal, 28'
  37. set label 2 "X = ".Counter(cnt) left at screen 0.75, 0.50 font 'Times New Roman:Normal, 28'
  38. set label 3 "{/symbol:Italic p} = ".Approx(cnt, i) left at screen 0.75, 0.44 font 'Times New Roman:Normal, 28'
  39. # Set range for plotting
  40. set xrange [0:1]
  41. set yrange [0:1]
  42. plot 'data.dat' using 1:($3==1 ? $2 : 1/0) every ::0::(i-1) with points pt 7 ps 0.4 lc rgb 'royalblue',\
  43. 'data.dat' using 1:($3==0 ? $2 : 1/0) every ::0::(i-1) with points pt 7 ps 0.4 lc rgb 'orange'
  44. }
  45.  
  46. set out

montecarlo.gif

Search This Blog

Translate

QooQ