Using Randomize() before Rnd() in VB.NET

2019-01-15 20:11发布

I have previously been told that I should always use Randomize() before I use Rnd() in a VB.NET application. Yet, it always seems to work fine without it. What does adding Randomize() do for me in this case?

It doesn't appear to affect my application in the least.

标签: vb.net random
3条回答
ら.Afraid
2楼-- · 2019-01-15 20:42

In Visual Basic, Rnd() uses a mathematical operation to produce the next "random" number. Because the actual operation is known, given a specific value, you can predict the next value. However, given an arbitray start value the numbers have good distribution - these are "pseudo-random" numbers.

To keep Rnd() from startng at a predictable number (and hence giving the same sequence of "random" numbers every time), Randomize() should be called to use the machine clock to set the initial value (called a seed).

(In the .NET world, I'd use System.Random instead if you can.)

查看更多
孤傲高冷的网名
3楼-- · 2019-01-15 20:53

Randomize will set the seed to something time related, like the system uptime or the system date. So the function Rand() will show different values every time the app is executed. However, I highly recommend you to use the System.Random class instead of VisualBasic Rand(). No need to call any randomize() function

Here are some example code, this will generate six random integers from the lower to upper bounds:

Dim randObj As New Random( seed )
Dim j As Integer
For j = 0 To 5
    Console.Write( "{0,11} ", randObj.Next( lower, upper ) )
Next j
Console.WriteLine( )
查看更多
成全新的幸福
4楼-- · 2019-01-15 20:57

Randomize() initializes the first seed of Rnd(). If you won't use it - VB.NET will use the default seed number.

查看更多
登录 后发表回答