PowerShell/scripts/list-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
Lists PI
.DESCRIPTION
2022-12-04 10:23:03 +01:00
This PowerShell script calculates and lists 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
2023-08-06 21:35:36 +02:00
PS> ./list-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
#>
2022-12-04 10:23:03 +01:00
param([int]$Digits = 1000)
2022-11-30 14:27:07 +01:00
function List-Pi ( $Digits ) {
$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
while ($ndigits -lt $Digits) {
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
}
Write-Host "... ($Digits digits)"
2022-11-30 14:27:07 +01:00
}
try {
List-Pi $Digits
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
}