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 “WriteHost $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 = 0 while ($last1 –ne $last2) { # WriteHost $last1 $last3 = $last2 $last2 = $last1 $last1 /= 2 } WriteHost "The smallest double is $last3. After that, we get $last2"
# Minimum using the [single] data type
[single] $last1 = 1 [single] $last2 = 0 [single] $last3 = 0 while ($last1 –ne $last2) { # WriteHost $last1 $last3 = $last2 $last2 = $last1 $last1 /= 2 } WriteHost "The smallest single is $last3. After that, we get $last2"
# Maximum using the [double] data type
[double] $last1 = 1 [double] $last2 = 0 [double] $last3 = 0 while ($last1 –ne $last2) { # WriteHost $last1 $last3 = $last2 $last2 = $last1 $last1 *= 2 } WriteHost "The largest double is $last3. After that, we get $last2"
# Maximum using the [single] data type
[single] $last1 = 1 [single] $last2 = 0 [single] $last3 = 0 while ($last1 –ne $last2) { # WriteHost $last1 $last3 = $last2 $last2 = $last1 $last1 *= 2 } WriteHost "The largest single is $last3. After that, we get $last2"
# # Sample output # # The smallest double is 4.94065645841247E324. After that, we get 0 # The smallest single is 1.401298E45. 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 #
