次の方法で共有


PowerShell Examples: Calculating very small and very large numbers

This blog is part of a series that shows example PowerShell code for those learning the language.

This time we’re using PowerShell to find some very small and very large floating point numbers. The principal here is that if you keep dividing a number by 2, there will be a point where the number is so small that you get zero when you divide it. In a similar fashion, if you keep multiplying a number by 2, there will be a point that the number is so large that it’s considered to be “infinity”.

This example shows details about the differently floating point data types ([single] and [double]) and also shows the use of while loops.

You might want to remove the comment on the “Write-Host $last1” line to show the progression to the final number in each example.

# PowerShell lessons# Calculating minimum and maximum numbers

cls

# Minimum using the [double] data type

[double] $last1 = 1[double] $last2 = 0[double] $last3 = 0while ($last1 –ne $last2) { # Write-Host $last1 $last3 = $last2 $last2 = $last1 $last1 /= 2 }Write-Host "The smallest double is $last3. After that, we get $last2"

# Minimum using the [single] data type

[single] $last1 = 1[single] $last2 = 0[single] $last3 = 0while ($last1 –ne $last2) { # Write-Host $last1 $last3 = $last2 $last2 = $last1 $last1 /= 2 }Write-Host "The smallest single is $last3. After that, we get $last2"

# Maximum using the [double] data type

[double] $last1 = 1[double] $last2 = 0[double] $last3 = 0while ($last1 –ne $last2) { # Write-Host $last1 $last3 = $last2 $last2 = $last1 $last1 *= 2 }Write-Host "The largest double is $last3. After that, we get $last2"

# Maximum using the [single] data type

[single] $last1 = 1[single] $last2 = 0[single] $last3 = 0while ($last1 –ne $last2) { # Write-Host $last1 $last3 = $last2 $last2 = $last1 $last1 *= 2 }Write-Host "The largest single is $last3. After that, we get $last2"

## Sample output ## The smallest double is 4.94065645841247E-324. After that, we get 0# The smallest single is 1.401298E-45. After that, we get 0# The largest double is 8.98846567431158E+307. After that, we get Infinity# The largest single is 1.701412E+38. After that, we get Infinity#