Last active
August 29, 2015 14:16
-
-
Save dohyunkim/c95a52f5d2aa3f430209 to your computer and use it in GitHub Desktop.
buffon's needle with luamplib
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| \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