Programmerare, skeptiker, sekulärhumanist, antirasist.
Författare till bok om C64 och senbliven lantis.
Röstar pirat.
2009-06-28
I might be wrong here, but the Random class in the .NET Framework looks fairly random to me. I tried this code to generate an image to see if any patterns would show up:
Using B As New System.Drawing.Bitmap(400, 400) Dim R As New Random() For Y As Integer = 0 To (B.Height - 1) For X As Integer = 0 To (B.Width - 1) Dim C As Integer = R.Next(0, 256) B.SetPixel(X, Y, Color.FromArgb(C, C, C)) Next Next B.Save("RandomClass.png") End Using
The generated image looks fine to me.
For referense, I tried to do the same thing with “true random generator” by the user Phill64 (from here) and the result look quite the same. This is the function:
Private Function GetRandomInt() As Integer Dim r As New Security.Cryptography.RNGCryptoServiceProvider() Dim bt(15) As Byte r.GetNonZeroBytes(bt) Dim d As Double = bt(0) For i As Integer = 1 To 15 d *= bt(i) Next d /= (10 ^ (Math.Floor(d).ToString.Length)) d -= Math.Floor(d) Return CType(d * 255, Integer) End Function
This is my adapted code to generate an image using this function instead of the .NET Random class:
Using B As New System.Drawing.Bitmap(400, 400) For Y As Integer = 0 To (B.Height - 1) For X As Integer = 0 To (B.Width - 1) Dim C As Integer = Me.GetRandomInt() B.SetPixel(X, Y, Color.FromArgb(C, C, C)) Next Next B.Save("Custom.png") End Using
No predictable patterns here either, but it the code was much slower.
The GetRandomInt function is a true random number generator, so if randomness matters, something like that is what you should use, but the Random class is fine most of the times. True randomness is much more important for Java programmers since the java.util.Random class produces obvious patterns.
Categories: Microsoft .NET
Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll!
Leave a Reply