Random Numbers?!

  • Thread starter Thread starter Hareth
  • Start date Start date
H

Hareth

Is this the correct way to generate random number?

Dim myRandomObject As Random

myRandomObject = New Random

myRandomObject.Next(1, 4)
 
Hareth said:
Is this the correct way to generate random number?

Dim myRandomObject As Random

myRandomObject = New Random

myRandomObject.Next(1, 4)

'Next' will /return/ the number:

\\\
Dim Generator As New Random()
Dim RandomValue As Integer = Generator.Next(1, 5)
///

.... will return a pseudo-random number between 1 and 4 (including 1 and 4).
 
It totally depends upon the usage of that Random #. If you are using that #
as ID for some records and its to large # of data is excepted, then use GUID
which is again one kind of Random #. But if you are using for some temporary
logic and which is short, then use Random class.

Mayur
 
You should supply a seed value when you instantiate the random class so that
you get different sequences of random numbers each time the routine runs.

Dim myRandomObject As New Random(Now.GetHashCode)
Dim randomNumber as Integer = myRandomObject.Next(1, 4)

Be aware that the code above will never return "4". In other words, the
upper limit you specify will never actually be reached. If you want to get
a random number that could be 1, 2, 3 or 4, you should supply "5" as the
upper limit).
 
Scott M. said:
You should supply a seed value when you instantiate the random class so
that you get different sequences of random numbers each time the routine
runs.

Dim myRandomObject As New Random(Now.GetHashCode)
Dim randomNumber as Integer = myRandomObject.Next(1, 4)

The parameterless ctor of 'Random' will use a time-dependent seed value,
which makes it unlikely that you get the same sequence of pseudo-random
numbers twice. There is no benefit in using 'Now.GetHashCode' over using
the parameterless constructor.
 
ACK

Herfried K. Wagner said:
The parameterless ctor of 'Random' will use a time-dependent seed value,
which makes it unlikely that you get the same sequence of pseudo-random
numbers twice. There is no benefit in using 'Now.GetHashCode' over using
the parameterless constructor.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top