School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become an Expert!

Join 307,138 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 1,799 people online right now. Registration is fast and FREE... Join Now!




Random Numbers

 
Reply to this topicStart new topic

> Random Numbers, How to generate them?

AdamSpeight2008
Group Icon



post 10 Mar, 2009 - 12:56 PM
Post #1


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
Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!

jens
Group Icon



post 13 Mar, 2009 - 12:23 PM
Post #2
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 this snippet.

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

/Jens

This post has been edited by jens: 13 Mar, 2009 - 12:34 PM
Go to the top of the page
+Quote Post

AdamSpeight2008
Group Icon



post 13 Mar, 2009 - 01:06 PM
Post #3
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.
Go to the top of the page
+Quote Post

AdamSpeight2008
Group Icon



post 13 Mar, 2009 - 01:33 PM
Post #4
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


Go to the top of the page
+Quote Post

crepitus
Group Icon



post 11 Sep, 2009 - 07:15 PM
Post #5
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!)
Go to the top of the page
+Quote Post


Fast ReplyReply to this topicStart new topic
2 User(s) are reading this topic (2 Guests and 0 Anonymous Users)
0 Members:

 


Lo-Fi Version Time is now: 11/21/09 03:20PM

Live Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month