Skip to content

Instantly share code, notes, and snippets.

@dohyunkim
Last active August 29, 2015 14:16
Show Gist options
  • Select an option

  • Save dohyunkim/c95a52f5d2aa3f430209 to your computer and use it in GitHub Desktop.

Select an option

Save dohyunkim/c95a52f5d2aa3f430209 to your computer and use it in GitHub Desktop.
buffon's needle with luamplib
\input luamplib.sty
\mplibnumbersystem{double}
\mplibtextextlabel{enable}
\ifdefined\n\else \def\n{5000}\fi
\ifdefined\length\else \def\length{100}\fi
\ifdefined\distance\else \def\distance{100}\fi
\ifnum\length>\distance \let\length\distance\fi
\mplibcode
total := \n; l := \length; d := \distance;
path needle, hline;
beginfig(0);
hline := (-1/2l,0) -- (3/2l,0);
draw hline; draw hline shifted (d*up);
strike := 0;
for i=1 upto total:
posx := uniformdeviate(l); posy := uniformdeviate(d);
ang := uniformdeviate(180);
needle := (dir ang * -l/2 -- dir ang * l/2) shifted (posx, posy);
if i <= 50: draw needle withcolor red; fi
if (ypart point 1 of needle >= d) or (ypart point 0 of needle <= 0):
strike := strike + 1;
fi
endfor
pi_a := 2*l*total/(d*strike);
label.rt("$n = " & decimal total & "$", 20*down);
label.rt("$\pi \approx " & decimal pi_a & "$", 30*down);
endfig;
\endmplibcode
\end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment