Skip to content
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

Add Monte Carlo in PowerShell #760

Merged
merged 1 commit into from
Sep 15, 2021
Merged
Show file tree
Hide file tree
Changes from all 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/powershell/MonteCarlo.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
function Is-InCircle($x, $y, $radius=1) {
return ([Math]::Pow($x, 2) + [Math]::Pow($y, 2)) -lt [Math]::Pow($radius, 2)
}

function Monte-Carlo([int]$n) {
$PiCount = 0;
for ($i = 0; $i -lt $n; $i++) {
$x = Get-Random -Minimum 0.0 -Maximum 1.0
$y = Get-Random -Minimum 0.0 -Maximum 1.0

if (Is-InCircle $x $y) {
$PiCount++
}
}
return 4.0 * $PiCount / $n
}

# This could take some time
$PiEstimate = Monte-Carlo 10000000
Write-Host "The pi estimate is: $PiEstimate"
Write-Host "Percent error is: $(100 * [Math]::Abs($PiEstimate - ([Math]::PI)) / ([Math]::PI))"
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 @@ -99,6 +99,8 @@ each point is tested to see whether it's in the circle or not:
</p>
{% sample lang="coco" %}
[import:4-9, lang:"coconut"](code/coconut/monte_carlo.coco)
{% sample lang="ps1" %}
[import:1-3, lang:"powershell"](code/powershell/MonteCarlo.ps1)
{% endmethod %}

If it's in the circle, we increase an internal count by one, and in the end,
Expand Down Expand Up @@ -206,6 +208,8 @@ The code snippets were taken from this [scratch project](https://scratch.mit.edu
</p>
{% sample lang="coco" %}
[import, lang:"coconut"](code/coconut/monte_carlo.coco)
{% sample lang="ps1" %}
[import, lang:"powershell"](code/powershell/MonteCarlo.ps1)
{% endmethod %}

<script>
Expand Down