I wrote a function to randomize a list and got weirdly biased results. Maybe because Random() was instantiated inside the function body. See this simple example and how the results differ. What am I missing? How should I use Random inside a function?
Function testshuffle() As Integer
Dim rng As New Random
Return rng.Next(4)
End Function
Dim listO As New List(Of String)
For i = 1 To 100000
listO.Add(testshuffle.ToString)
Next
Debug.WriteLine(listO.FindAll(Function(p) p = "0").Count.ToString, "0")
Debug.WriteLine(listO.FindAll(Function(p) p = "1").Count.ToString, "1")
Debug.WriteLine(listO.FindAll(Function(p) p = "2").Count.ToString, "2")
Debug.WriteLine(listO.FindAll(Function(p) p = "3").Count.ToString, "3")
the result is:
0: 30393
1: 17924
2: 15162
3: 36521
on the other hand this code:
Dim r As New Random
For i = 1 To 100000
listO.Add(r.Next(4).ToString)
Next
results in :
0: 24743
1: 25086
2: 25028
3: 25143
Aucun commentaire:
Enregistrer un commentaire