Random number generator in c# - again

  • Thread starter Piotr 'Zenobius' Baranowski
  • Start date
P

Piotr 'Zenobius' Baranowski

Hello :)

I've got lame begginer question about generating different random
numbers in C# ;-)

First, some code:
public int test(int lb)
{
int count = 0;
Random randSeed = new Random();

for(int i=0;i<lb;i++)
{
double test = randSeed.NextDouble();
if(test>0.49) {
count++;
}
}
return count;
}

The code _should_ give me all positive scores of 'lb' throws of coin.
And it does. But when called couple of times in the "same" time, like:

test(23); test(12); test(45);

it generates the same scores..

How do i hop over it in C# ? ;-)
 
G

Guest

Hi Piort,
I am not sure what you mean by "hop over it" but you can try to make it
more random by adding a seed to the constructor of the random class, or
create the random class outside of your test method and pass it in so that
all counts use the same random object i.e.

Random r = new Random((int)DateTime.Now.Ticks);

test(23, r);
test(15, r);
test(45, r);

Or if you want truley random numbers you might want to try using
System.Security.Cryptography.RandomNumberGenerator which will give you better
results, but I believe will be slower.

Hope that helps
Mark R Dawson
 
J

Jon Skeet [C# MVP]

The code _should_ give me all positive scores of 'lb' throws of coin.
And it does. But when called couple of times in the "same" time, like:

test(23); test(12); test(45);

it generates the same scores..

How do i hop over it in C# ? ;-)

Just create a single Random and use it repeatedly. By default, the
current time is used for the initial seed for a new Random instance. If
you create two Randoms at the same time (as you are doing, effectively)
you'll get the same results multiple times.
 
P

Piotr 'Zenobius' Baranowski

Jon said:
Just create a single Random and use it repeatedly. By default, the
current time is used for the initial seed for a new Random instance. If
you create two Randoms at the same time (as you are doing, effectively)
you'll get the same results multiple times.

This works the same, 2-4 scores are the same ;-)

I just wanted to create function, that simulates real k2 rolls.. now i'm
using Random.Next(lb+1), and it works fine.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top