开发者

Random class does not create random number? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Why is Random class isn't really random?

I have following kind of code:

public static int GenerateRandomNumber(int seed)
{
    var random = new Random(seed);                
    int num = random.Next();
    while(num.ToString().Length != 6){
        num = random.Next();
    }
    return开发者_如何转开发 num;
}

I want to get different number every time when call this function even with same seed. But I always got same result. For example, every time when call GenerateRandomNumber(1), I always got number 640839.

How to fix this problem?


I want to get different number every time when call this function even with same seed.

Since that is the opposite of what the Random constructor is documented to do, you are going to have to learn to live with disappointment. You can't always get what you want.


Here is your problem:

var random = new Random(id); 

Random generates a pseudo-random set of results - for the same seed, you would get the same sequence every time.

Change the creation of the Random object to a static field and you will get a different result whenever you call it.

From MSDN - Random Class:

The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated.


Random creates a series of pseudo-random numbers based on an initial value called a seed (id in your code).

Since the seed is identical then all calls to the function will follow the same code-path and generate the same result.

Make the random = new Random(seed) a static variable in your function or make it a member in the containing class and pass it to all functions/classes that need it.

Consider using a time based seed value when you are done developing the program.


I want to get different number every time when call this function even with same seed.

That's not how seeds work. The whole point of a seed is that using the same seed will result in the same series of pseudo-random numbers. The series is deterministic


The problem you need to fix is to align your expectations with the product specifications:

Providing an identical seed value to different Random objects causes each instance to produce identical sequences of random numbers.

So either expect the same sequence froma seed, or don't use a seed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜