diff --git a/contents/monte_carlo_integration/code/powershell/MonteCarlo.ps1 b/contents/monte_carlo_integration/code/powershell/MonteCarlo.ps1 new file mode 100644 index 000000000..fe80d6db0 --- /dev/null +++ b/contents/monte_carlo_integration/code/powershell/MonteCarlo.ps1 @@ -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))" \ No newline at end of file diff --git a/contents/monte_carlo_integration/monte_carlo_integration.md b/contents/monte_carlo_integration/monte_carlo_integration.md index 4256009b8..ac6895404 100644 --- a/contents/monte_carlo_integration/monte_carlo_integration.md +++ b/contents/monte_carlo_integration/monte_carlo_integration.md @@ -99,6 +99,8 @@ each point is tested to see whether it's in the circle or not:

{% 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, @@ -206,6 +208,8 @@ The code snippets were taken from this [scratch project](https://scratch.mit.edu

{% sample lang="coco" %} [import, lang:"coconut"](code/coconut/monte_carlo.coco) +{% sample lang="ps1" %} +[import, lang:"powershell"](code/powershell/MonteCarlo.ps1) {% endmethod %}