Printable Version of Topic

Click here to view this topic in its original format

Dream.In.Code _ VB.NET Tutorials _ Random Numbers

Posted by: AdamSpeight2008 10 Mar, 2009 - 12:56 PM

Sometimes in your programs you require a touch of randomness.

So you write a section of code like the following.

CODE

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Randomize()
        x = Math.Floor(Rnd() * 6) + 1
    End Sub

But when you run it, it only returns the same number.

The .net framework provides you with a solution.
CODE

Dim MyRandomNumber As New Random()

I personally like using
CODE

Dim MyRandomNumber As New Random(Now.Milliseconds)

Why the Now.Milliseconds?

By using Now.Milliseconds as the seed for the Random Number Generator, makes it less likely that the sequence of numbers will be repeated.

Now after you defined your Random Number Generator (MyRandomNumber) you'll want to be able to utilize it.
There different ways of getting a random number out it.

A Random Integer (Positive Only)
CODE

Dim x As Integer
x=MyRandomNumber.Next


A Random Integer 0 - ?
CODE

Dim x As Integer
x=MyRandomNumber.Next(10)

The numbers are from 0 up to but not including 10

[b]A Random Integer From A up to B
CODE

Dim x As Integer
x=MyRandomNumber.Next(65, 91)

In this case between 65 & 90 inclusive.

In the case of Double it's a little different.
You can only have a random double which has a value between 0 and 1.
CODE

Dim x As Double
x=MyRandomNumber.NextDouble


What if you want a random double between 0 and 100 (inclusive)?
Treat the value of the random double as if it was a percentage of some other value. Example
CODE

Dim x As Double
x==MyRandomNumber.NextDouble * 100


For a in-between value it not so easy. So I create a Function to do it for you.
CODE

Private Function RandomDouble_Between(ByRef RnG As Random,ByVal FromValue As Double, ByVal ToValue As Double) As Double
If RnG Is Nothing Then Return Double.NaN
If FromValue>ToValue Then Return Double.NaN
Dim Delta As Double = ToValue - FromValue
Return (RnG.NextDouble * Delta) + FromValue
End Function

CODE

Dim x As Double
x=RandomDouble_Between(MyRandomNumber, 65,91)


You may have notice that the a Random Number Generator has the follow method .Bytes and wonder what it does.
It makes it easy to generate an array full of random bytes.
CODE

Dim TheArray(9) As Byte
MyRandomNumber.NextBytes(TheArray)


I hope you find the contents of this tutorial useful. ph34r.gif

Posted by: jens 13 Mar, 2009 - 12:23 PM

Very good walkthrough pertaining to random numbers. I'd like to address a quirk though. If you need several random numbers and call a random number function several times very close in time (i.e. within the same millisecond) you'll end up using the same seed (the time in ms) and you'll get repeating random numbers. There's a way to avoid this (which of course have been provided by me cool.gif ) by creating a list of random numbers from one seed. This is implemented in http://www.dreamincode.net/code/snippet2787.htm.

With Adams explanations and this snippet you'll be real random number ph34r.gif . biggrin.gif

/Jens

Posted by: AdamSpeight2008 13 Mar, 2009 - 01:06 PM

It depends at on how you define random and what its being used for.

For crypto. needs there is.

CODE

Dim rn As System.Security.Cryptography.RandomNumberGenerator = System.Security.Cryptography.RandomNumberGenerator.Create()

But this can only provide on it own a random filled array.

Posted by: AdamSpeight2008 13 Mar, 2009 - 01:33 PM

Had a thought about same number issue, it can happen is declare two differently name RNGs with the same seed.

So you could just declare one Random Number Generator outside of the Function, sub or Method.
Then use that one.

CODE

Module RandomExample
Public rn As New Random(Now.Millisecond)

Public Function ThrowOfDie() As Inte
  Return rn.next(1,7)
End Function

End Module



Posted by: crepitus 11 Sep, 2009 - 07:15 PM

If you use reflector to look at the constructor for the Random class, you'll see:

CODE
Public Sub New()
    Me.New(Environment.TickCount)
End Sub


So, there's no need to pass in Now.Millisecond - just use the parameterless constructor.

(Plus, if you use Now.Millisecond, then you will have 1000 different seeds. That's not very many!)

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)