-
-
Notifications
You must be signed in to change notification settings - Fork 357
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
added MonteCarlo in PowerShell (#760)
- Loading branch information
Showing
2 changed files
with
25 additions
and
0 deletions.
There are no files selected for viewing
21 changes: 21 additions & 0 deletions
21
contents/monte_carlo_integration/code/powershell/MonteCarlo.ps1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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))" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters