当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Random class does not create random number?

问题描述:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: