Skip to content

Commit 2333f3b

Browse files
authored
adding matlab implementation to monte carlo integration (#696)
1 parent d46b897 commit 2333f3b

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
pi_estimate = monte_carlo(10000000);
2+
3+
fprintf("The pi estimate is: %f\n", pi_estimate);
4+
fprintf("Percent error is: %f%%\n", 100 * abs(pi_estimate - pi) / pi);
5+
6+
function pi_estimate=monte_carlo(n)
7+
8+
% a 2 by n array, rows are xs and ys
9+
xy_array = rand(2, n);
10+
11+
% square every element in the array
12+
squares_array = xy_array.^2;
13+
14+
% sum the xs and ys and check if it's in the quarter circle
15+
incircle_array = sum(squares_array)<1;
16+
17+
% determine the average number of points in the circle
18+
pi_estimate = 4*sum(incircle_array)/n;
19+
20+
end
21+

contents/monte_carlo_integration/monte_carlo_integration.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,8 @@ each point is tested to see whether it's in the circle or not:
9191
[import:2-10, lang:"bash"](code/bash/monte_carlo.bash)
9292
{% sample lang="kotlin" %}
9393
[import:3-3, lang:"kotlin"](code/kotlin/MonteCarlo.kt)
94+
{% sample lang="m" %}
95+
[import:8-15, lang:"matlab"](code/matlab/monte.m)
9496
{% sample lang="scratch" %}
9597
<p>
9698
<img class="center" src="code/scratch/InCircle.svg" style="width:40%" />
@@ -193,6 +195,8 @@ Feel free to submit your version via pull request, and thanks for reading!
193195
[import, lang:"bash"](code/bash/monte_carlo.bash)
194196
{% sample lang="kotlin" %}
195197
[import, lang:"kotlin"](code/kotlin/MonteCarlo.kt)
198+
{% sample lang="m" %}
199+
[import, lang:"matlab"](code/matlab/monte.m)
196200
{% sample lang="scratch" %}
197201
The code snippets were taken from this [scratch project](https://scratch.mit.edu/projects/319610349)
198202
<p>

0 commit comments

Comments
 (0)