Skip to content

adding matlab implementation to monte carlo integration #696

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
May 24, 2020
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions contents/monte_carlo_integration/code/matlab/monte.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
pi_estimate = monte_carlo(10000000);

fprintf("The pi estimate is: %f\n", pi_estimate);
fprintf("Percent error is: %f%%", 100 * abs(pi_estimate - pi) / pi);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changes added!

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just one thing, can you add a newline after Percent error is?


function pi_estimate=monte_carlo(n)

% a 2 by n array, rows are xs and ys
xy_array = rand(2, n);

% square every element in the array
squares_array = xy_array.^2;

% sum the xs and ys and check if it's in the quarter circle
incircle_array = sum(squares_array)<1;

% determine the average number of points in the circle
pi_estimate = 4*sum(incircle_array)/n;

end

4 changes: 4 additions & 0 deletions contents/monte_carlo_integration/monte_carlo_integration.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,8 @@ each point is tested to see whether it's in the circle or not:
[import:2-10, lang:"bash"](code/bash/monte_carlo.bash)
{% sample lang="kotlin" %}
[import:3-3, lang:"kotlin"](code/kotlin/MonteCarlo.kt)
{% sample lang="m" %}
[import:8-15, lang:"matlab"](code/matlab/monte.m)
{% sample lang="scratch" %}
<p>
<img class="center" src="code/scratch/InCircle.svg" width="314" />
Expand Down Expand Up @@ -193,6 +195,8 @@ Feel free to submit your version via pull request, and thanks for reading!
[import, lang:"bash"](code/bash/monte_carlo.bash)
{% sample lang="kotlin" %}
[import, lang:"kotlin"](code/kotlin/MonteCarlo.kt)
{% sample lang="m" %}
[import, lang:"matlab"](code/matlab/monte.m)
{% sample lang="scratch" %}
The code snippets were taken from this [scratch project](https://scratch.mit.edu/projects/319610349)
<p>
Expand Down