@dbasnett の回答を拡張して、優れたジェネリック ジェネレーターを作成したので、この質問に頭を悩ませると思いました。
注: Decimal を使用しましたが、Double を出力として代用しても問題はありません。
''' <summary>
''' Random Decimal generator with variable precision"
''' </summary>
''' <param name="L">Minimum Value</param>
''' <param name="U">Maximum Value</param>
''' <param name="P">Precision</param>
''' <returns>Decimal</returns>
''' <remarks></remarks>
Private Function DRandom(L As Integer, U As Integer, P As Integer) As Decimal
Dim Rand As New Random
Dim Upper As String = U.ToString
Dim Precision As String = "1"
For I = 0 To P
If I > 0 Then
If I = P Then
Upper = Upper + "1"
Else
Upper = Upper + "0"
End If
Precision = Precision + "0"
End If
Next
Return Rand.Next(L, Upper.toInteger) / Precision.toInteger
End Function
私の一般的な toInteger 拡張を使用すると、次のようになります。
''' <summary>
''' Handles conversion of variable to Integer.
''' </summary>
''' <param name="X"></param>
''' <param name="I">Returned if conversion fails.</param>
''' <returns>Signed 32bit Integer</returns>
''' <remarks></remarks>
<Runtime.CompilerServices.Extension()> _
Public Function toInteger(Of T)(ByRef X As T, Optional I As Integer = 0) As Integer
Dim S As String = X.ToString
Try
If S = String.Empty Then
Return I
Else
Return Integer.Parse(S)
End If
Catch
Dim result As String = String.Empty
Dim ReturnInt As Integer
Dim Parsed As Byte
For Each Character In S.ToCharArray
If Character = "-" Then
If S.Substring(0, 1).ToString <> "-" Then
result = Character + result
End If
End If
If Character = "." Then
Exit For
End If
If Byte.TryParse(Character, Parsed) Then
result = result + Parsed.ToString
End If
Next
If result <> String.Empty Then
If Integer.TryParse(result, ReturnInt) Then
Return Integer.Parse(ReturnInt)
Else
If Double.Parse(result) > Double.Parse(Integer.MaxValue.ToString) Then
Return Integer.MaxValue
ElseIf Double.Parse(result) < Double.Parse(Integer.MinValue.ToString) Then
Return Integer.MinValue
Else
Return I
End If
End If
Else
Return I
End If
End Try
End Function
このジェネレーターは可変精度を使用するだけでなく、乱数ジェネレーターの最大の再利用性 (私の意見では) を許可する上限と下限をコードで選択できるようにします。
これが人々に役立つことを願っています。