Skip to content

Commit

Permalink
added MonteCarlo in PowerShell (#760)
Browse files Browse the repository at this point in the history
  • Loading branch information
PaddyKe authored Sep 15, 2021
1 parent f04abdc commit 7bae159
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
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

0 comments on commit 7bae159

Please sign in to comment.