diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index a1ad4161d..9197efd50 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -5,3 +5,4 @@ Gathros Jeremie Gillet (- Jie -) Salim Khatib Hitesh C +Jonas Vander Vennet diff --git a/chapters/monte_carlo/code/python3/monte_carlo.py b/chapters/monte_carlo/code/python3/monte_carlo.py new file mode 100644 index 000000000..5f0603a05 --- /dev/null +++ b/chapters/monte_carlo/code/python3/monte_carlo.py @@ -0,0 +1,20 @@ +#example submitted by Jonas Vander Vennet, Python 3.5.2 + +import random, math + +# function to determine whether an x, y point is inside a circle with given radius +def in_circle(x, y, radius): + return x**2 + y**2 < radius**2 + +# function to integrate a circle with given radius via monte carlo integration +def monte_carlo(n, radius): + count = 0 + for i in range(n): + count += in_circle(random.uniform(0,radius),random.uniform(0,radius),radius) + return 4*(count/n)*radius**2 + +#estimate pi by integrating the unit circle +estimated_pi = monte_carlo(10**6, 1) + +print("percent error: {:%}".format(abs(estimated_pi-math.pi)/math.pi)) +print("Estimation for pi: {:f}".format(estimated_pi)) \ No newline at end of file diff --git a/chapters/monte_carlo/monte_carlo.md b/chapters/monte_carlo/monte_carlo.md index f7e9290a1..4f484fffd 100644 --- a/chapters/monte_carlo/monte_carlo.md +++ b/chapters/monte_carlo/monte_carlo.md @@ -41,6 +41,8 @@ each point is tested to see whether it's in the circle or not: [import:2-8, lang:"julia"](code/julia/monte_carlo.jl) {% sample lang="hs" %} [import:7-7, lang:"haskell"](code/haskell/monteCarlo.hs) +{% sample lang="py3" %} +[import:5-7, lang:"python"](code/python3/monte_carlo.py) {% endmethod %} If it's in the circle, we increase an internal count by one, and in the end, @@ -78,6 +80,9 @@ Feel free to submit your version via pull request, and thanks for reading! {% sample lang="hs" %} ### Haskell [import, lang:"haskell"](code/haskell/monteCarlo.hs) +{% sample lang="py3" %} +### Python 3 +[import, lang:"python"](code/python3/monte_carlo.py) {% endmethod %}