PowerShell/scripts/write-pi.ps1

75 lines
1.7 KiB
PowerShell
Raw Normal View History

2024-10-01 15:11:03 +02:00
<#
2022-11-30 14:27:07 +01:00
.SYNOPSIS
2024-10-28 14:12:31 +01:00
Writes PI
2022-11-30 14:27:07 +01:00
.DESCRIPTION
2024-10-28 14:12:31 +01:00
This PowerShell script calculates and writes the digits of the mathematical constant PI.
2022-11-30 14:27:07 +01:00
.PARAMETER digits
2022-12-04 10:23:03 +01:00
Specifies the number of digits to list (1000 by default)
2022-11-30 14:27:07 +01:00
.EXAMPLE
2024-10-28 14:12:31 +01:00
PS> ./write-pi.ps1
2022-11-30 14:27:07 +01:00
3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342...
.LINK
2022-12-04 10:23:03 +01:00
https://github.com/fleschutz/PowerShell
2022-11-30 14:27:07 +01:00
.NOTES
2022-12-04 10:23:03 +01:00
Author: Markus Fleschutz | License: CC0
2022-11-30 14:27:07 +01:00
#>
2024-10-28 14:12:31 +01:00
param([int]$digits = 1000)
2022-11-30 14:27:07 +01:00
2024-10-28 14:12:31 +01:00
function Write-Pi ( $digits ) {
2022-11-30 14:27:07 +01:00
$Big = [bigint[]](0..10)
$ndigits = 0
$q = $t = $k = $Big[1]
$r = $Big[0]
$l = $n = $Big[3]
# calculate first digit
$nr = ( $Big[2] * $q + $r ) * $l
$nn = ( $q * ( $Big[7] * $k + $Big[2] ) + $r * $l ) / ( $t * $l )
$q *= $k
$t *= $l
$l += $Big[2]
$k = $k + $Big[1]
$n = $nn
$r = $nr
Write-Host "$($n)." -noNewline
$ndigits++
$nr = $Big[10] * ( $r - $n * $t )
$n = ( ( $Big[10] * ( 3 * $q + $r ) ) / $t ) - 10 * $n
$q *= $Big[10]
$r = $nr
2024-10-28 14:12:31 +01:00
while ($ndigits -lt $digits) {
2022-11-30 14:27:07 +01:00
if ($Big[4] * $q + $r - $t -lt $n * $t) {
Write-Host "$n" -noNewline
$ndigits++
$nr = $Big[10] * ( $r - $n * $t )
$n = ( ( $Big[10] * ( 3 * $q + $r ) ) / $t ) - 10 * $n
$q *= $Big[10]
$r = $nr
} else {
$nr = ( $Big[2] * $q + $r ) * $l
$nn = ( $q * ( $Big[7] * $k + $Big[2] ) + $r * $l ) / ( $t * $l )
$q *= $k
$t *= $l
$l += $Big[2]
$k = $k + $Big[1]
$n = $nn
$r = $nr
}
2022-12-04 10:23:03 +01:00
}
2024-10-28 14:12:31 +01:00
Write-Host "... ($digits digits)"
2022-11-30 14:27:07 +01:00
}
try {
2024-10-28 14:12:31 +01:00
Write-Pi $digits
2022-11-30 14:27:07 +01:00
exit 0 # success
} catch {
2022-12-29 21:46:35 +01:00
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
2023-08-06 21:35:36 +02:00
}