Skip to content

Commit 30b71e1

Browse files
committed
modifying function to return its value and print outside
1 parent 76cf2bb commit 30b71e1

File tree

2 files changed

+24
-0
lines changed

2 files changed

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

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:7-14, lang:"matlab"](code/matlab/monte.m)
9496
{% sample lang="scratch" %}
9597
<p>
9698
<img class="center" src="code/scratch/InCircle.svg" width="314" />
@@ -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)