Skip to content

Commit 7bae159

Browse files
authored
added MonteCarlo in PowerShell (#760)
1 parent f04abdc commit 7bae159

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+
function Is-InCircle($x, $y, $radius=1) {
2+
return ([Math]::Pow($x, 2) + [Math]::Pow($y, 2)) -lt [Math]::Pow($radius, 2)
3+
}
4+
5+
function Monte-Carlo([int]$n) {
6+
$PiCount = 0;
7+
for ($i = 0; $i -lt $n; $i++) {
8+
$x = Get-Random -Minimum 0.0 -Maximum 1.0
9+
$y = Get-Random -Minimum 0.0 -Maximum 1.0
10+
11+
if (Is-InCircle $x $y) {
12+
$PiCount++
13+
}
14+
}
15+
return 4.0 * $PiCount / $n
16+
}
17+
18+
# This could take some time
19+
$PiEstimate = Monte-Carlo 10000000
20+
Write-Host "The pi estimate is: $PiEstimate"
21+
Write-Host "Percent error is: $(100 * [Math]::Abs($PiEstimate - ([Math]::PI)) / ([Math]::PI))"

contents/monte_carlo_integration/monte_carlo_integration.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,8 @@ each point is tested to see whether it's in the circle or not:
9999
</p>
100100
{% sample lang="coco" %}
101101
[import:4-9, lang:"coconut"](code/coconut/monte_carlo.coco)
102+
{% sample lang="ps1" %}
103+
[import:1-3, lang:"powershell"](code/powershell/MonteCarlo.ps1)
102104
{% endmethod %}
103105

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

211215
<script>

0 commit comments

Comments
 (0)