This question already has answers here:
Random number generator only generating one random number
(15 answers)
Closed 9 years ago.
having an issue generating random numbers in a loop. Can get around it by using Thread.Sleep but after a more elegant solution.
for ...
Random r = new Random();
string += r.Next(4);
Will end up with 11111... 222... etc.
Suggestions?
Move the declaration of the random number generator out of the loop.
The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated. One way to produce different sequences is to make the seed value time-dependent, thereby producing a different series with each new instance of Random. By default, the parameterless constructor of the Random class uses the system clock to generate its seed value, ...
Source
By having the declaration in the loop you are effectively calling the constructor with the same value over and over again - hence you are getting the same numbers out.
So your code should become:
Random r = new Random();
for ...
string += r.Next(4);
Random r = new Random();
for ...
string += r.Next(4);
new Random() will initialize the (pseudo-)random number generator with a seed based on the current date and time. Thus, two instances of Random created at the same date and time will yield the same sequence of numbers.
You created a new random number generator in each iteration and then took the first value of that sequence. Since the random number generators were the same, the first value of their sequences was the same. My solution will create one random number generator and then return the first, the second, etc... value of the sequence (which will be different).
I found a page in Chinese that said the same with the time: http://godleon.blogspot.hk/2007/12/c.html, it said if you type like this:
Random random = new Random(Guid.NewGuid().GetHashCode());
you MAY get a random number even in a loop! It solved my question as well!
You should be using the same Random instance throughout instead of creating a new one each time.
As you have it:
for ...
Random r = new Random();
string += r.Next(4);
the seed value is the same for each (it defaults to the current timestamp) so the value returned is the same.
By reusing a single Random instance like so:
Random r = new Random()
for ...
string += r.Next(4);
Each time you call r.Next(4) the values are updated (basically a different seed for each call).
Move the Random r = new Random(); outside the loop and just call next inside the loop.
Related
Hello there I want to generate random numbers, so I created method in my class
private readonly Random _rand = new Random(); //Private property of class
public void GenerateRandomNumber()
{
//For loop executes 10 times
for (int i = 1; i < 11; i++)
{
Console.WriteLine(_rand.Next(0, 10));
}
}
When I call this from Main I create new instance of my class and then call it. It works properly but I want to know why does this generate different numbers each time in for loop and also each time I run the program?
That's interesting for me because I know that Random can generate same numbers but in my case it generates different ones.
How will it affect if I add static modifier to private property?
In C# your random number generator will automatically set the seed to a value based on your system clock, thus generating pseudo random numbers. If you would like your random numbers to be in the same order every time you run the program you can manually set the seed using:
seed = 999
private readonly Random _rand = new Random(seed)
The Random object is not what's generating the numbers. When calling _rand.Next(0, 10), it's generating a random number between 0 and 9 which is why you are getting new numbers each time. See the documentation for Random.Next(). If you only want one random number, you will need to call this method outside of the loop and store the result in a variable.
This question already has answers here:
Random number generator only generating one random number
(15 answers)
Closed 6 years ago.
public string Weird
{
get
{
int length = 10;
Random random = new Random();
string chars = "123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXZ";
StringBuilder builder = new StringBuilder(length);
for (int i = 0; i < length; i++)
{
builder.Append(chars[random.Next(chars.Length)]);
}
return builder.ToString();
}
}
Response.Write(Weird);
Response.Write("<br />");
Response.Write(Weird);
Response.Write("<br />");
Response.Write(Weird);
Result :
9eFZ5XrJxZ
9eFZ5XrJxZ
9eFZ5XrJxZ
I thought the result would be different for each call, but it return same result value.
How it could be?
Once the variable assigned then the get method will not run again?
From http://msdn.microsoft.com/en-us/library/system.random.aspx:
The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated. One way to produce different sequences is to make the seed value time-dependent, thereby producing a different series with each new instance of Random.
By default, the parameterless constructor of the Random class uses the system clock to generate its seed value, while its parameterized constructor can take an Int32 value based on the number of ticks in the current time. However, because the clock has finite resolution, using the parameterless constructor to create different Random objects in close succession creates random number generators that produce identical sequences of random numbers.
If you can't make the Random object persist between calls you need to seed it with a pseudorandom value every time you call into that.
Dilbert has encountered the same problem back in 2001:
http://dilbert.com/strips/comic/2001-10-25/
Coincidence?
I don't think so.
And random.org agrees :
http://www.random.org/analysis/
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Why does it appear that my random number generator isn't random in C#?
I have the following code:
int a;
int aa;
Random aRand = new Random();
Random aaRand = new Random();
a = aRand.Next(20);
aa = aaRand.Next(20);
//if (a == aa)
{
Console.WriteLine(a + " " + aa);
Console.ReadLine();
}
I'm assuming that aRand and aaRand would be two different values, but that's not the case. What am I doing wrong? I'm assuming that aRand and aaRand will not always be the same, but they keep coming out the same all the time.
Thanks
This is explicitly covered in the docs for Random():
The default seed value is derived from the system clock and has finite
resolution. As a result, different Random objects that are created in
close succession by a call to the default constructor will have
identical default seed values and, therefore, will produce identical
sets of random numbers.
Why are you creating two different Random variables? You could use just one:
int a;
int aa;
Random aRand = new Random();
a = aRand.Next(20);
aa = aRand.Next(20);
//if (a == aa)
{
Console.WriteLine(a + " " + aa);
Console.ReadLine();
}
Edit:
"The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated. One way to produce different sequences is to make the seed value time-dependent, thereby producing a different series with each new instance of Random. By default, the parameterless constructor of the Random class uses the system clock to generate its seed value, while its parameterized constructor can take an Int32 value based on the number of ticks in the current time. "
from http://msdn.microsoft.com/en-us/library/system.random.aspx
You only need one instance of Random() - just call .Next() twice.
int a;
int aa;
Random aRand = new Random();
a = aRand.Next(20);
aa = aRand.Next(20);
You should never have more than One Random variable in your entire application. Get rid of the second
Random aaRand = new Random();
It looks like the two instances are using the same seed.
the seed determines all the values that will be generated and in which order. If you create 200 instances of Random with the same seed, they'll all give you the same output.
Create a single Instance when your app starts and reuse it.
I'm working on Pong in C# w/ XNA.
I want to use a random number (within a range) to determine things such as whether or not the ball rebounds straight, or at an angle, and how fast the ball moves when it hits a paddle.
I want to know how to implement it.
Use the Random class. For example:
Random r = new Random();
int nextValue = r.Next(0, 100); // Returns a random number from 0-99
Unless you need cryptographically secure numbers, Random should be fine for you... but there are two gotchas to be aware of:
You shouldn't create a new instance every time you need one. If you create an instance without specifying a seed, it will use the current time as the seed - which means if you create several instances in quick succession, many of them will produce the same sequence of numbers. Typically you create a long-lasting instance of Random and reuse it.
It's not thread-safe. If you need to generate random numbers from multiple threads, you should think about having one instance per thread. Read this blog post for more information - but make sure you read the comments as well, as they have very useful information.
Random rnd = new Random();
rnd.Next(minValue, maxValue);
i.e.
rnd.Next(1,10);
Use the Random object's Next method that takes a min and max and returns a value in that range:
var random = new Random();
int randomNum = random.Next(min, max);
While you can use the Random class like all the other are suggesting, the Random class only uses psuedo-random number generation. The RandomNumberGenerator, which can be found in the System.Security.Cryptography namespace, creates actual random numbers.
How To Use:
RandomNumberGenerator rng = RandomNumberGenerator.Create();
byte[] rand = new byte[25]; //Set the length of this array to
// the number of random numbers you want
rng.GetBytes(rand);
More Info: http://msdn.microsoft.com/en-us/library/system.security.cryptography.randomnumbergenerator(v=VS.80).aspx
Here is my random generator
private static Random rnd = new Random(Environment.TickCount);
private int RandomNum(int Lower, int Upper)
{
return rnd.Next(Lower, Upper);//MyRandomNumber;
}
Ive taken over some prize drawing code.
I can see the person is using a Random number to order them by but is this actually going to be random as i cant see any place where he has done oRand.Next(); Does the default Random generate an actual random number.
Random oRand = new Random();
var res = (from l in listNew.AsQueryable<Participant>() //entities.Participant
where l.Status != 0
select l).AsEnumerable().OrderBy(p=>oRand);
Does the default Random generate an
actual random number.
In the example code you are ordering by the "RandomNumberMaker" (i.e. the same value for all values), not by random numbers.
This is quickly tested by comparing this code in LINQPad (which yields the numbers 1 to 1000 in natural order).
void Main()
{
Random oRand = new Random();
var res = Enumerable.Range(1, 1000).OrderBy(p=>oRand);
res.Dump();
}
with this code (which orders the numbers 1 to 1000 in pseudorandom order):
void Main()
{
Random oRand = new Random();
var res =Enumerable.Range(1, 1000).OrderBy(p=>oRand.Next());
res.Dump();
}
For an intro to how random .NET random really is, check out this article which has the advantage of starting with this great comic:
(source: csharpcity.com)
I think you need oRand.Next() to get random numbers. This looks like it would end up ordering them by the Random object. I don't see how using oRand by itself would result in the lambda expression calling Next().
In any case, when you use oRand = new Random(); oRand.Next();, you get pseudorandom numbers using time as a seed. This means that there is a sequence of numbers that is the same every time, and the one you start with depends on the time -- this is usually done with a function that you pass the last random number to get the next one and it has a very long period and the numbers have a random feel (so it's not just f(x) => x+1 or something like that).
This may not be good enough, but it is "random" for some definition of random.