Need to generate different random numbers - c#

I need help in trying to generate a random number because with my coding below it shows the same number in both text boxes.
private int RandomNumber(int min, int max)
{
Random random = new Random();
random.Next();
return random.Next(1, 7); // random integer and assigned to number
}
private void button1_Click(object sender, EventArgs e)
{
tb1.Text = RandomNumber(1, 7).ToString(); // Random Number for Text Box 1.
tb2.Text = RandomNumber(7, 1).ToString(); // Random Number for Text Box 2.
}

Random picks a seed based on the current time.
If you create two Randoms at the same time, they will give you the same numbers.
Instead, you need to create a single Random instance and store it in a field in your class.
However, beware that Random is not thread-safe.

You need to instantiate your Random class only once. From MSDN, the documentation states that:
If the same seed is used for separate Random objects, they will generate the same series of random numbers.
In your case, as SLaKs also said, the seed is the current time. You're calling the functions so close together they are using the same seed. If you move the instantiation outside of the function, you have one instance based on one seed, instead of multiple objects based on the same seed.
Random random = new Random();
private int RandomNumber(int min, int max)
{
return random.Next(1, 7); // random integer and assigned to number
}

You need to create the Random object outside of your function. Creating a new one each time you need a new random number will result in the seed being identical (given the time gap between creations)

Related

What exactly does the parameter seed in MLContext do? [duplicate]

This is my code to generate random numbers using a seed as an argument:
double randomGenerator(long seed) {
Random generator = new Random(seed);
double num = generator.nextDouble() * (0.5);
return num;
}
Every time I give a seed and try to generate 100 numbers, they all are the same.
How can I fix this?
If you're giving the same seed, that's normal. That's an important feature allowing tests.
Check this to understand pseudo random generation and seeds:
Pseudorandom number generator
A pseudorandom number generator (PRNG), also known as a deterministic
random bit generator DRBG, is an algorithm for generating a sequence
of numbers that approximates the properties of random numbers. The
sequence is not truly random in that it is completely determined by
a relatively small set of initial values, called the PRNG's state,
which includes a truly random seed.
If you want to have different sequences (the usual case when not tuning or debugging the algorithm), you should call the zero argument constructor which uses the nanoTime to try to get a different seed every time. This Random instance should of course be kept outside of your method.
Your code should probably be like this:
private Random generator = new Random();
double randomGenerator() {
return generator.nextDouble()*0.5;
}
The easy way is to use:
Random rand = new Random(System.currentTimeMillis());
This is the best way to generate Random numbers.
You shouldn't be creating a new Random in method scope. Make it a class member:
public class Foo {
private Random random
public Foo() {
this(System.currentTimeMillis());
}
public Foo(long seed) {
this.random = new Random(seed);
}
public synchronized double getNext() {
return generator.nextDouble();
}
}
This is only an example. I don't think wrapping Random this way adds any value. Put it in a class of yours that is using it.
That's the principle of a Pseudo-RNG. The numbers are not really random. They are generated using a deterministic algorithm, but depending on the seed, the sequence of generated numbers vary. Since you always use the same seed, you always get the same sequence.
Problem is that you seed the random generator again. Every time you seed it the initial state of the random number generator gets reset and the first random number you generate will be the first random number after the initial state
If you'd want to generate multiple numbers using one seed you can do something like this:
public double[] GenerateNumbers(long seed, int amount) {
double[] randomList = new double[amount];
for (int i=0;i<amount;i++) {
Random generator = new Random(seed);
randomList[i] = Math.abs((double) (generator.nextLong() % 0.001) * 10000);
seed--;
}
return randomList;
}
It will display the same list if you use the same seed.
Several of the examples here create a new Random instance, but this is unnecessary. There is also no reason to use synchronized as one solution does. Instead, take advantage of the methods on the ThreadLocalRandom class:
double randomGenerator() {
return ThreadLocalRandom.current().nextDouble(0.5);
}

Why doesn't this create a "true" random number? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Random number generator only generating one random number
Im trying to create a loop to create and output 5 random numbers in a listbox. Basically it outputs the same random number 5 times instead of 5 different ones. When I use a break point and go through the code it does actually generate the 5 numbers. So why does it only output the first answer? Thank you. (This is not the entirety of the project, but I need to get this working first).
public string Numbertext1;
public string Numbertext2;
public int GeneratedNumbers;
public int Average = 0;
public int TotalSum = 0;
public int TotalCalcs = 0;
public int Counter = 0;
private void btnRandomise_Click(object sender, EventArgs e)
{
Numbertext1 = txtNum1.Text;
int Number1;
int.TryParse(Numbertext1, out Number1);
Numbertext2 = txtNum2.Text;
int Number2;
int.TryParse(Numbertext2, out Number2);
do
{
Random num = new Random();
int number = num.Next(Number1, Number2);
lbNumbers.Items.Add(Convert.ToString(number));
Counter++;
}
while (Counter < 5);
{
TotalCalcs++;
Counter = 0;
}
}
}
}
You need to initialize your num variable at the global level. It's using the same seed over and over again.
Put this : Random num = new Random(); at the top where you are initializing everything else. Then remove it from inside your method.
It's because you're creating a new Random instance within a tight loop, so the seed number will be the same. The Random class is not truly random (in the mathematical sense), so you should change the seed or use one instance of it. Move Random num = new Random(); to the top with the other variables.
Because you didn't adequately seed the random number generator.
The generator has an algorithmn it follows, if you just create it without seeding it then your numbers will be the same each time. To quote from MSDN:
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.
To fix this use the other constructor which allows you to specify a seed - there is a good example of this on MSDN.
The Random class instantiation is time-dependent. With a very quick loop, you're creating the same object every time and thus you're getting the same value over and over. You need to move the instantiation outside the loop so you get new numbers when you call Next() .
This is also the reason why it "works" when you use a break point to check the values. The Random object you created will have different reference times and thus would be different.

Why does Random.Next() always return the same number [duplicate]

This question already has answers here:
Random number generator only generating one random number
(15 answers)
Closed 7 years ago.
Consider this method:
private static int GenerateRandomNumber(int seed, int max)
{
return new Random(seed).Next(max);
}
On my machine, executing this loop yields the same number through 1500 iterations:
for (int i = 0; i < 1501; i++)
{
int random = GenerateRandomNumber(100000000, 999999999);
Console.WriteLine(random.ToString());
Console.ReadKey();
}
I get 145156561, for every single iteration.
I don't have a pressing issue, I was just curious about this behavior because .Next(max) says "Returns a Non Negative random number less than the specified maximum. Perhaps I am not understanding something basic.
You're always seeding a new instance with the same seed, and then grabbing the first max. By using a Seed, you're guaranteeing the same results.
If you want to have a static, random number generation that does different results, you should rework this a bit. However, since Random is not threadsafe, it requires some synchronization when used statically. Something like:
private static Random random;
private static object syncObj = new object();
private static void InitRandomNumber(int seed)
{
random = new Random(seed);
}
private static int GenerateRandomNumber(int max)
{
lock(syncObj)
{
if (random == null)
random = new Random(); // Or exception...
return random.Next(max);
}
}
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/
The problem is that you are creating a new Random instance with the same seed number each time. You should create a single Random instance (store it in a static if necessary) and simply call the next method on that same instance.
Random number generation is not truly random, see this Wikipedia entry for more details.
Salam to All,
Well it drove me crazy as well. The answer is simple. Change the seed before you generate random.
Example:
I want to generate random number between 1 to 10
Random rnd = new Random(DateTime.Now.Second);
int random_number = rnd.Next(10);
Put it inside a loop and run it three times. It will give out random numbers below 10.
Pseudo-random number generator usually work by choosing a seed, and then generating a deterministic sequence based on that seed. Choosing the same seed every time, you generate the same sequence.
There are "only" 2^32 different random sequences in .NET.
Not sure how the internals work.. check wiki for it, but it's very simple.
public class MathCalculations
{
private Random rnd = new Random();
public Int32 getRandom(Int32 iMin, Int32 iMax)
{
return rnd.Next(iMin, iMax);
}
}
public class Main
{
MathCalculations mathCalculations = new MathCalculations();
for (int i = 0; i < 6; i++)
{
getRandom(0,1000);
}
}
will generate Number1, Number2, Number3, Number4, Number5, Number6 (1 seed, 1 sequence of many numbers, random*not really, but approx.*)
if you however do this:
public class MathCalculations
{
public Int32 getRandom(Int32 iMin, Int32 iMax)
{
Random rnd = new Random();
return rnd.Next(iMin, iMax);
}
}
public class Main
{
MathCalculations mathCalculations = new MathCalculations();
for (int i = 0; i < 6; i++)
{
getRandom(0,1000);
}
}
You will now get Number1, Number1, Number1, Number1, Number1, Number1 (1 seed, 6 equal sequences of many numbers, always pick the same starting number from each equal sequence).. At some point Number1 will be different, because the seed changes over time.. but you need to wait some time for this, nonetheless, you never pick number2 from the sequence.
The reason is, each time you generate a new sequence with the same seed, hence the sequence is the same over and over again, and each time your random generated will pick the first number in it's sequence, which, with the same seed, is of course always the same.
Not sure if this is technically correct by the underlying methods of the random generator, but that's how it behaves.
In the event that anyone is looking for a "quick and dirty" "solution" (and I use that term with caution) then this will suffice for most.
int secondsSinceMidnight = Convert.ToInt32(DateTime.Now.Subtract(DateTime.Today).TotalSeconds);
Random rand = new Random(secondsSinceMidnight);
var usuallyRandomId = rand.Next();
Please note my use of usually random. I agree that the item marked as the answer is a more correct way of doing this.

Correct method of a "static" Random.Next in C#?

Why do i need to create an instance of Random class, if i want to create a random number between 1 and 100 ....like
Random rand = new Random();
rand.Next(1,100);
Is there any static function of Random class to do the same? like...
Random.Next(1,100);
I don't want to create an instance unnecessarily
It is best practice to create a single instance of Random and use it throughout your program - otherwise the results may not be as random. This behavior is encouraged by not creating a static function.
You shouldn't worry about "creating an instance unnecessarily", the impact is negligible at best - this is the way the framework works.
//Function to get random number
private static readonly Random random = new Random();
private static readonly object syncLock = new object();
public static int RandomNumber(int min, int max)
{
lock(syncLock) { // synchronize
return random.Next(min, max);
}
}
Copied directly from
It's not "unnecessary", because the Random class stores some state internally. It does that to make sure that if you call .Next() multiple times very quickly (in the same millisecond or tick or whatever) you still won't get the same number.
Of course, if that's not a problem in your case you can always combine those two lines of code into one:
new Random().Next(1, 100);
You already got answers here. Just reiterating the right solution:
namespace mySpace
{
public static class Util
{
private static Random rnd = new Random();
public static int GetRandom()
{
return rnd.Next();
}
}
}
So you can call:
var i = Util.GetRandom();
all throughout. If you strictly need a true stateless static method to generate random numbers, you can rely on a Guid.
public static class Util
{
public static int GetRandom()
{
return Guid.NewGuid().GetHashCode();
}
}
It's going to be a wee bit slower, but can be much more random than Random.Next, at least from my experience.
But not:
new Random(Guid.NewGuid().GetHashCode()).Next();
The unnecessary object creation is going to make it slower especially under a loop.
And never:
new Random().Next();
Not only its slower (inside a loop), it's randomness is... well not really good according to me..
From MSDN: Random Class (System):
"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. The following example illustrates that two Random objects that are instantiated in close succession generate an identical series of random numbers..."
Wikipedia explains PRNGs
The best way to do it is to have a ThreadStatic Random instance:
[ThreadStatic] static Random random;
Random Get() {
if (random == null) random = new Random(Guid.NewGuid().GetHashCode());
return random;
}
This takes care of everything.
Thread safety
Performance
No need to seed
It eludes me why the .NET Framework (and any other framework on earth) does not use something in this spirit.
Creating a new instance of Random then calling it immediately multiple times, e.g.:
for (int i = 0; i < 1000; i++)
{
Random rand = new Random();
Console.WriteLine(rand.Next(1,100));
}
Will give you a distribution that is weighted towards the lower end of the range.
Doing it this way:
Random rand = new Random();
for (int i = 0; i < 1000; i++)
{
Console.WriteLine(rand.Next(1,100));
}
Will give you a better distribution.
Why not?
You need to create an instance because the way random numbers are generated is that previous answers affect subsequent answers. By default, the new Random() constructor uses the current system time to "seed" the sequence, but it doesn't have to: you can pass your own number in if you like. In particular:
var rand = new Random(1234);
Console.WriteLine(rand.Next(0, 100));
Console.WriteLine(rand.Next(0, 100));
Console.WriteLine(rand.Next(0, 100));
Console.WriteLine(rand.Next(0, 100));
Will produce the same sequence of "random" number every time.
That means the Random class needs to keep instance data (the previous answer, or "seed") around for subsequent calls.
Creating a short-lived instance in C# is almost free. Don't waste your time worrying about this. You probably have better places to look for perf or memory gains.
Random number generators must maintain state in order to be "random." The random number generator creates a sequence that is generated based on a random seed. The problem is that nothing in a computer is actually random. The closest thing the computer has at hand is the system clock; that is the effectively the time at which the process takes place. So by default the current tick count of the system clock is used. If your application is fast enough then many random number calculations may occur under the same system tick. If the random number generator doesn't maintain state at all, it will provide the same random number multiple times (same input gives the same output). This is not usually what you want.
I know its already answered, but I just have to say that I prefer to use the singleton pattern in this case.
You need something similar to this if you want the syntax you mention.
namespace MyRandom
{
public class Random
{
private static m_rand = new Random();
public static Next(int min, int max)
{
return m_rand.Next(min, max);
}
}
}
This should allow you to do Random.Next(1,100); without having to worry about seeding.

Create a random int number that differ from previous run of program

I use this code to generate a random number.
Random R = new Random(0);
int Rand = R.Next(7);
but i get the same random number in each run of program.
Remove the 0 from the constructor and you'll get different random numbers.
If you pass a number to the constructor it's used as seed, by always specifying 0 you'll always get the same sequence.
You can specify an int32 which is random, but the easiest is to just not pass any parameter and you get a timebased seed
you have to change the seed of your random number generator object everytime you run your program, as what i've seen from you example, your current seed is 0, so you have to change it to something else if you want to get a different stream of random number... just a thought!
Seed your (pseudo)-random generator using a non-constant value, e.g. current time and date:
Random R = new Random(DateTime.Now.Ticks);
Read more about pseudo-random generators at Wikipedia.
Use time as initial seed of your PRNG.
You need to seed the random generator. You can use as follows:
Random R = new Random(DateTime.Now.Millisecond);
int Rand = R.Next(7);
Random number generators generate a new 'random' value based on the previous number generated. The seed is the initial value for this.
Seeding with the same value (like 0 in your example code) basically tells the random number generator to start with the same number each time. Having the exact same random number generated each time means your code becomes restartable. Example: Simulations use this to restart the simulation with changed parameters, but with the same 'data set'.
Another example:
I want to send myself a motivational message each day. Sometimes the messages are garbled. Being able to rerun the script, producing the same message again and again during a day, makes fixing this simple. In Perl code this means:
# By initialising the random generator with the day number since
# the epoch, we get the same quote during one day.
srand(time()/(24*3600));
my $i = int(rand(#messages));
If you want to produce different numbers each time, you will have to set this seed to something random. The options are many, like time, PID, delay between two keystrokes by the user, some value derived from the ethernet interface, etc. or more likely a combination of the above like time*PID.
Hope this clarifies the idea behind the concept of a random number seed value.
if we want a random number between 1 and 100 the code would look like this:
RandomNumberGenerator.GetRandomInt(1, 100)
The most secure way to generate random number is to use the System.Security.Cryptography.RandomNumberGenerator class.
Here is an example that will generate a number between 1 and 100;
public Number Rand()
{
byte[] Salt = new byte[8];
System.Security.Cryptography.RandomNumberGenerator.Create().GetBytes(Salt);
decimal result = 0;
foreach (byte b in Salt)
{
result = result * 255 + b;
}
while (result > 100)
{
result /= 10;
}
return result
}
Complete Code:
public static class RandomHelper
{
static object _myLock = new object();
static Random _random = new Random();
public static int RandomNumber(int min, int max)
{
lock (_myLock)
{
if (min == max)
return min;
if (min > max)
return _random.Next(max, min);
return _random.Next(min, max);
}
}
You need to seed the Random class with something more variable than 0. I normally use DataTime.Now.Ticks or you could use a new Guid's integer value.

Categories

Resources