Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / Languages / C# / May 2007

Tip: Looking for answers? Try searching our database.

how good is .NET's Random for making random numbers?

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
Zytan - 16 May 2007 03:09 GMT
Anyone do any tests on it?  I would assume it has improved since C's
rand(), but who knows.  For some reason, and it could just be
coincidence, I seem to see patterns.  But even a crappy rand()
function should be good enough to avoid that, so i may be seeing
things.

Zytan
Marc Gravell - 16 May 2007 05:02 GMT
Are you re-using a Randomobject, or creating a new one each time? Note
that the seed is time-based and is not high-def, so if you use new
Random() in a tight loop you will get batches of the same numbers. a
static (locked) Random instance can be useful in some scenarios; I
believe Jon has a StaticRand class (or similar) in his misc.utils. If
you want more "randomness" then use a cryptographic random, which this
isn't. But they are more expensive.

As for patters: over what range? Statistically you simply will see
similar numbers occasionally...

Marc
Zytan - 16 May 2007 16:44 GMT
> Are you re-using a Randomobject, or creating a new one each time? Note
> that the seed is time-based and is not high-def, so if you use new
> Random() in a tight loop you will get batches of the same numbers.

I should have stated that I wasn't doing this.  I create one instance,
using the default time.

> As for patters: over what range? Statistically you simply will see
> similar numbers occasionally...

It seems that the similar numbers pop up twice in a row sometimes, far
too often.  Yes, I know this should happen, but without going and
making a test to see how random it is, I was wondering if it was
already done.  I want to know if it's better than C's rand().

Zytan
Jon Skeet [C# MVP] - 16 May 2007 19:09 GMT
> > As for patters: over what range? Statistically you simply will see
> > similar numbers occasionally...
>
> It seems that the similar numbers pop up twice in a row sometimes, far
> too often.

How often, with what range? Can you tell us more about what you're
doing?

Signature

Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet   Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

Zytan - 21 May 2007 15:29 GMT
> > It seems that the similar numbers pop up twice in a row sometimes, far
> > too often.
>
> How often, with what range? Can you tell us more about what you're
> doing?

No, not without analysis that would take too much time.  I'm sure even
with C's crappy rand() function that it can be shown that it is pretty
random, and such repetitions are normal, as they are with real random
numbers.

My only concern was whether .NET's Random() is better than C's
rand()...?  I could see patterns in C's rand() fairly easy, without
even looking specifically for them.

Zytan
Jon Davis - 16 May 2007 06:34 GMT
I always create a exactly one single static Random object with my app and
seed it with DateTime.Now.Ticks.

Jon

> Anyone do any tests on it?  I would assume it has improved since C's
> rand(), but who knows.  For some reason, and it could just be
[quoted text clipped - 3 lines]
>
> Zytan
Jon Skeet [C# MVP] - 16 May 2007 07:33 GMT
> I always create a exactly one single static Random object with my app and
> seed it with DateTime.Now.Ticks.

Random already seeds itself with Environment.TickCount if you don't
provide any constructor parameters.

You need to watch for using a single object in a multi-threaded
situation though - Random isn't thread-safe.

Signature

Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet   Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

Jon Davis - 16 May 2007 07:46 GMT
>> I always create a exactly one single static Random object with my app and
>> seed it with DateTime.Now.Ticks.
>
> Random already seeds itself with Environment.TickCount if you don't
> provide any constructor parameters.

True, but specifying the ticks gives me a stub I can modify later.

> You need to watch for using a single object in a multi-threaded
> situation though - Random isn't thread-safe.

Since Next() always scrambles its seed, regardless of calling thread, why is
this of concern?

Jon
Jon Davis - 16 May 2007 07:55 GMT
>>> I always create a exactly one single static Random object with my app
>>> and
[quoted text clipped - 5 lines]
> Since Next() always scrambles its seed, regardless of calling thread, why
> is this of concern?

Come to think of it, multiple threads are *exactly* the reason why you
should use exactly one static Random in an app, unless you're really trying
to create collisions.

Jon
Jon Skeet [C# MVP] - 16 May 2007 08:57 GMT
On May 16, 7:46 am, "Jon Davis" <j...@REMOVE.ME.PLEASE.jondavis.net>
wrote:
> > You need to watch for using a single object in a multi-threaded
> > situation though - Random isn't thread-safe.
>
> Since Next() always scrambles its seed, regardless of calling thread, why is
> this of concern?

If Next() is called from two threads at the same time, they could both
get to the "reading" point of the code at the same time, and see the
same value, which probably isn't desirable. If you got two threads in
lock-step they could see the same whole sequence of numbers - unlikely
as

Furthermore, because it's not documented as being thread-safe it
wouldn't be entirely unreasonable for Random to just break in a multi-
threaded situation. I don't think it does in the current
implementation, but I don't like calling things which aren't designed
for multi-threaded use in a multi-threaded way.

My StaticRandom class uses a single Random object, but serializes
access to it. As each call is very fast, it's unlikely that there will
be performance issues and it's just that bit safer. It's also easier
to use from your own code - just call StaticRandom.Next etc :)

Jon
Jon Davis - 16 May 2007 09:33 GMT
> On May 16, 7:46 am, "Jon Davis" <j...@REMOVE.ME.PLEASE.jondavis.net>
> wrote:
[quoted text clipped - 7 lines]
> If Next() is called from two threads at the same time, they could both
> get to the "reading" point of the code at the same time,

Uhm... I never said one should disregard thread locking.

public static Random AppRandom = new Random();
public static int NextRandom
{
   get { lock (typeof(Program)) { return AppRandom.Next(); } }
}

> My StaticRandom class ...

Not to shrug off your ever-important opportunity to toot your own horn, my
point is that by sticking to only one static Random in the app you nearly
eliminate the risk of two parallel Random objects ending up with the same
seed or an eventual sequential match of pattern between instances.

Jon
Nicholas Paldino [.NET/C# MVP] - 16 May 2007 16:09 GMT
Depending on the distribution you need, if you need a random number
generator which won't be so predictable, you can consider the
RNGCryptoServiceProvider class in the System.Security.Cryptography
namespace.  You still have the issues with thread-safety, but you will get a
much more random distribution of numbers.

Signature

         - Nicholas Paldino [.NET/C# MVP]
         - mvp@spam.guard.caspershouse.com

>> On May 16, 7:46 am, "Jon Davis" <j...@REMOVE.ME.PLEASE.jondavis.net>
>> wrote:
[quoted text clipped - 24 lines]
>
> Jon
Jon Skeet [C# MVP] - 16 May 2007 16:47 GMT
On May 16, 9:33 am, "Jon Davis" <j...@REMOVE.ME.PLEASE.jondavis.net>
wrote:
> > If Next() is called from two threads at the same time, they could both
> > get to the "reading" point of the code at the same time,
>
> Uhm... I never said one should disregard thread locking.

I must have misinterpreted you then. I wrote:

<quote>
You need to watch for using a single object in a multi-threaded
situation though - Random isn't thread-safe.
</quote>

and you responded:

<quote>
Since Next() always scrambles its seed, regardless of
calling thread, why is this of concern?
</quote>

I hope you can see why I interpreted this as effectively disregarding
the fact that Random isn't thread-safe.

> public static Random AppRandom = new Random();
> public static int NextRandom
[quoted text clipped - 8 lines]
> eliminate the risk of two parallel Random objects ending up with the same
> seed or an eventual sequential match of pattern between instances.

Leaving the personal attack to one side (any reason for that, by the
way? I'll readily admit there's nothing remotely clever in
StaticRandom - it's just handy to not have to reinvent the wheel,
that's all) I quite agree that using a static Random object is a good
idea, otherwise I wouldn't have written StaticRandom in the first
place.

All I said to start with is that you need to be careful. Clearly in
your code you *are* being careful (by locking) so I'm not sure what
the fuss is about.

Jon
Zytan - 16 May 2007 16:50 GMT
> my
> point is that by sticking to only one static Random in the app you nearly
> eliminate the risk of two parallel Random objects ending up with the same
> seed or an eventual sequential match of pattern between instances.

Yes, that's true.

Zytan
Samuel R. Neff - 16 May 2007 17:53 GMT
Slightly OT, but you should never lock on a Type.

http://msdn.microsoft.com/archive/default.asp?url=/archive/en-us/dnaraskdr/html/
askgui06032003.asp


In this particular example you already have a static variable
appropriate for locking anyways so no need to create a new
synchronization object, just lock AppRandom.

Also, since AppRandom is declared as public, then the locked behavior
is optional, making the whole thing not thread safe and locking
effectively pointless.

HTH,

Sam

------------------------------------------------------------
We're hiring!  B-Line Medical is seeking .NET
Developers for exciting positions in medical product
development in MD/DC.  Work with a variety of technologies
in a relaxed team environment.  See ads on Dice.com.

>public static Random AppRandom = new Random();
>public static int NextRandom
>{
>    get { lock (typeof(Program)) { return AppRandom.Next(); } }
>}
Jon Davis - 16 May 2007 19:00 GMT
> a fairly common practice (and one that's, unfortunately,
> described in some of our documentation right now,
> although we'll be fixing that) is actually quite problematic

It's really, REALLY freaking annoying when Microsoft writes, publishes, and
announces an elaborate article like this, but does not fix the one line of
documentation that contradicts it FIRST. :(

http://msdn2.microsoft.com/en-us/library/c5kehkcz(vs.71).aspx

Jon

> Slightly OT, but you should never lock on a Type.
>
[quoted text clipped - 23 lines]
>>    get { lock (typeof(Program)) { return AppRandom.Next(); } }
>>}
Jon Skeet [C# MVP] - 16 May 2007 19:14 GMT
> > a fairly common practice (and one that's, unfortunately,
> > described in some of our documentation right now,
[quoted text clipped - 5 lines]
>
> http://msdn2.microsoft.com/en-us/library/c5kehkcz(vs.71).aspx

Eek, that's terrible - not just for the typeof(...) bit, but also for
recommending locking on "this" which is also a no-no :(

I've done the whole "rate and give feedback" bit. Not sure whether
it'll help though.

Signature

Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet   Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

Göran Andersson - 18 May 2007 06:57 GMT
> In this particular example you already have a static variable
> appropriate for locking anyways so no need to create a new
> synchronization object, just lock AppRandom.

There is no need to create a synchronisation object, but you might want
to. :)

It's good to have a private object that is only used for the
synchronisation, that way there is no other code that can lock on the
same object (causing a deadlock), and as the object isn't used for
anything else you won't ever have any reason to make it public.

Signature

Göran Andersson
_____
http://www.guffa.com

Zytan - 16 May 2007 16:47 GMT
> Furthermore, because it's not documented as being thread-safe it
> wouldn't be entirely unreasonable for Random to just break in a multi-
> threaded situation. I don't think it does in the current
> implementation, but I don't like calling things which aren't designed
> for multi-threaded use in a multi-threaded way.

If they implemented any of the more complicated multi-dimension random
number generators that stores huge arrays of information, that are
incrementally indexed, you'll eventually find that the index is
increased twice on the last element (from two different threads) and
it will crash.  NET could potentially improve Random() to use such an
algorithm, and you would have to say byebye to your code.

> My StaticRandom class uses a single Random object, but serializes
> access to it. As each call is very fast, it's unlikely that there will
> be performance issues and it's just that bit safer. It's also easier
> to use from your own code - just call StaticRandom.Next etc :)

Thanks, I'll have to take a look at this.

Zytan
Alberto Poblacion - 16 May 2007 07:09 GMT
> Anyone do any tests on it?  I would assume it has improved since C's
> rand(), but who knows.  For some reason, and it could just be
> coincidence, I seem to see patterns.  But even a crappy rand()
> function should be good enough to avoid that, so i may be seeing
> things.

    If the Random class is not good enough for you, you may wish to take a
look at the System.Security.Cryptography.RNGCryptoServiceProvider, which
provides a cryptographically-robust random number generator.
Zytan - 16 May 2007 16:57 GMT
>      If the Random class is not good enough for you, you may wish to take a
> look at the System.Security.Cryptography.RNGCryptoServiceProvider, which
> provides a cryptographically-robust random number generator.

Ok, thanks, Alberto.  I don't need it to be secure, though, just more
random.  But, this would suit that purpose, as well.

Zytan
Arne Vajhøj - 19 May 2007 23:23 GMT
>> Anyone do any tests on it?  I would assume it has improved since C's
>> rand(), but who knows.  For some reason, and it could just be
[quoted text clipped - 5 lines]
> a look at the System.Security.Cryptography.RNGCryptoServiceProvider,
> which provides a cryptographically-robust random number generator.

Note that this class is not necessarily more random than the
normal Random.

It is just more secure in the sense that it is less predictable.

Arne
Peter Duniho - 16 May 2007 08:54 GMT
> Anyone do any tests on it?  I would assume it has improved since C's
> rand(), but who knows.  For some reason, and it could just be
> coincidence, I seem to see patterns.

Of course you see patterns.  You're human, and that's what humans are  
designed to do.

I'm reminded of my wife's complaint that one of the games I wrote would  
occasionally throw up two or more wild-card pieces in quick succession.  
"It's not random enough!"  It was a little hard to figure out the best way  
to explain that it was doing that exactly because it *was* random.  That  
if the wild-card pieces only showed up on specific intervals, then *that*  
would be an indication of lack of randomness.

Anyway, unless the patterns you see are something like "1, 2, 3, 4, 5, 6,  
7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9,  
10", you probably are "just seeing things" and I wouldn't worry about it  
if I were you.  :)

Pete
Zytan - 16 May 2007 16:59 GMT
> Anyway, unless the patterns you see are something like "1, 2, 3, 4, 5, 6,  
> 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9,  
> 10", you probably are "just seeing things" and I wouldn't worry about it  
> if I were you.  :)

I am 99.9% sure you are right, and i think the same thing, but I still
just want to know if it's better than the 3 lines of code C's rand()
was made from, since with extremely little effort, you could see
patterns.  Not like the above, but when shown in a visual way, where
you can 'see' the numbers' meanings (not their digits), you could see
the same stuff occured over and over again.  Especially if you made
sure to sequence them in groups of even binary numbers ;)

Zytan
Samuel R. Neff - 16 May 2007 18:25 GMT
You can always look at the Random class in Reflector to see exactly
what it does.  It's plain .NET managed code.

It's more than 3 lines, but not all that much more.  :-)

Sam

------------------------------------------------------------
We're hiring!  B-Line Medical is seeking .NET
Developers for exciting positions in medical product
development in MD/DC.  Work with a variety of technologies
in a relaxed team environment.  See ads on Dice.com.

>> Anyway, unless the patterns you see are something like "1, 2, 3, 4, 5, 6,  
>> 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9,  
[quoted text clipped - 10 lines]
>
>Zytan
Barry Kelly - 16 May 2007 18:51 GMT
> > Anyway, unless the patterns you see are something like "1, 2, 3, 4, 5, 6,  
> > 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9,  
[quoted text clipped - 4 lines]
> just want to know if it's better than the 3 lines of code C's rand()
> was made from, since with extremely little effort,

Typical C RTL rand() has poor randomness in low digits. You always had
to use division rather than modulus to get good results.

> you could see
> patterns.  Not like the above, but when shown in a visual way, where
> you can 'see' the numbers' meanings (not their digits), you could see
> the same stuff occured over and over again.  Especially if you made
> sure to sequence them in groups of even binary numbers ;)

It sounds like you may have been using modulus, which would have left
the least significant digits untouched, especially if your modulus was
even and you were grouping resulting numbers by even/odd.

-- Barry

Signature

http://barrkel.blogspot.com/

Zytan - 21 May 2007 15:35 GMT
> Typical C RTL rand() has poor randomness in low digits. You always had
> to use division rather than modulus to get good results.

Good point.  Very true.

> It sounds like you may have been using modulus, which would have left
> the least significant digits untouched, especially if your modulus was
> even and you were grouping resulting numbers by even/odd.

I'm not sure what the numbers were, I really didn't have enough
numbers to make a prope stab at whether or not it was random.  Just
the concern that it may not be, caused me to start this thread.

Thanks, Barry

Zytan
Göran Andersson - 16 May 2007 10:24 GMT
> Anyone do any tests on it?  I would assume it has improved since C's
> rand(), but who knows.  For some reason, and it could just be
[quoted text clipped - 3 lines]
>
> Zytan

As mentioned earlier, the most common reason for bad randomness is
creating several Random objects. If used correctly, the randomness is
pretty good.

If you create a very large number of random numbers, you will be able to
see some subtle patterns. If you for example pick colors by random for
every pixel in a large image, your brain will probably be able to
distinguish some patterns, as the random numbers are not completely random.

If you need really really really good randomness, there is a random
generator in the System.Security.Cryptography namespace. It's used to
create encryption keys, where the demands for randomness is extremely high.

Signature

Göran Andersson
_____
http://www.guffa.com

Zytan - 16 May 2007 17:04 GMT
> As mentioned earlier, the most common reason for bad randomness is
> creating several Random objects. If used correctly, the randomness is
> pretty good.

Yup, I am not doing this, so that's not the issue for me.

> If you create a very large number of random numbers, you will be able to
> see some subtle patterns. If you for example pick colors by random for
> every pixel in a large image, your brain will probably be able to
> distinguish some patterns, as the random numbers are not completely random.

Has anyone tried this?  I'd like to see the result.  I'll do it myself
if no one has.

> If you need really really really good randomness, there is a random
> generator in the System.Security.Cryptography namespace. It's used to
> create encryption keys, where the demands for randomness is extremely high.

Ok, thanks.

Zytan
mpetrotta@gmail.com - 16 May 2007 20:02 GMT
> > If you create a very large number of random numbers, you will be able to
> > see some subtle patterns. If you for example pick colors by random for
[quoted text clipped - 3 lines]
> Has anyone tried this?  I'd like to see the result.  I'll do it myself
> if no one has.

Seemed like an interesting thing to try.  Here you go:
http://www.petrotta.org/random.png
I can't spot any patterns in it, not that I expected to.  It's
interesting to note that compressing to png saved only 18 bytes out of
the 459K bitmap.  That's a sign of random data :-)

Here's the source.  It's a pretty naive (and slow) creation of an
image with random grayscale data.  I'm sure there are better ways to
do this.  I'd like to try creating 16bpp images too.

using System;
using System.Drawing;

namespace RandomGrays
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length != 3)
            {
                throw new ArgumentOutOfRangeException("Usage: randomgrays <width>
<height> <outfile>");
            }

            int width = Convert.ToInt32(args[0]);
            int height = Convert.ToInt32(args[1]);
            string fileName = args[2].ToString();
            Bitmap b = new Bitmap(width, height);
            Random r = new Random();
            for (int x = 0; x < width; x++)
            {
                for (int y = height - 1; y >= 0; y--) // eye scan order == write
order
                {
                    int random = r.Next(255);
                    b.SetPixel(x, y, Color.FromArgb(random, random, random));
                }
            }
            b.Save(fileName);
        }
    }
}

Michael
mpetrotta@gmail.com - 16 May 2007 20:16 GMT
> > If you create a very large number of random numbers, you will be able to
> > see some subtle patterns. If you for example pick colors by random for
[quoted text clipped - 3 lines]
> Has anyone tried this?  I'd like to see the result.  I'll do it myself
> if no one has.

(apologies if this is a repost.  I don't believe my first attempt went
out)

Seemed like an interesting thing to try.  Here you go:
http://www.petrotta.org/random.png

A 640x480 bitmap of random grayscale pixels.  Looks pretty random to
me, if a little bipolar.  A histogram shows that it's pretty flat
across the values, though.

Here's the source.  I'm sure there are better ways to do this, if only
because this was dead slow:

using System;
using System.Drawing;

namespace RandomGrays
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length != 3)
            {
                throw new ArgumentOutOfRangeException("Usage: randomgrays <width>
<height> <outfile>");
            }

            int width = Convert.ToInt32(args[0]);
            int height = Convert.ToInt32(args[1]);
            string fileName = args[2].ToString();
            Bitmap b = new Bitmap(width, height);
            Random r = new Random();
            for (int x = 0; x < width; x++)
            {
                for (int y = height - 1; y >= 0; y--) // eye scan order == write
order
                {
                    int random = r.Next(255);
                    b.SetPixel(x, y, Color.FromArgb(random, random, random));
                }
            }
            b.Save(fileName);
        }
    }
}

Michael
Zytan - 21 May 2007 15:43 GMT
> Seemed like an interesting thing to try.  Here you go:http://www.petrotta.org/random.png

Thanks.

> A 640x480 bitmap of random grayscale pixels.  Looks pretty random to
> me, if a little bipolar.  A histogram shows that it's pretty flat
> across the values, though.

I tried it with 256 and 512 widths, which really show the flaws in C's
rand(), but Random() seems to hold up well.

> Here's the source.  I'm sure there are better ways to do this, if only
> because this was dead slow:

I used int random = r.Next(256); to give 0..255 values (256 is
maximum, but it returns one less than max)

And, eye scan order starts at 0, not at the bottom.  Bitmaps are
stored in the file bottom up, but are still displayed with row 0 at
the top.

I think we can conclude Random() is better than C's rand().

Thanks, Michael

Zytan
Peter Bromberg [C# MVP] - 16 May 2007 12:21 GMT
"The generation of random numbers is far too important to be left to chance"
-- Robert Coveyou

Signature

Site:  http://www.eggheadcafe.com
UnBlog:  http://petesbloggerama.blogspot.com
Short urls & more:    http://ittyurl.net

> Anyone do any tests on it?  I would assume it has improved since C's
> rand(), but who knows.  For some reason, and it could just be
[quoted text clipped - 3 lines]
>
> Zytan
Alun Harford - 16 May 2007 15:15 GMT
> Anyone do any tests on it?  I would assume it has improved since C's
> rand(), but who knows.  For some reason, and it could just be
> coincidence, I seem to see patterns.  But even a crappy rand()
> function should be good enough to avoid that, so i may be seeing
> things.

Here are some random numbers:

5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5.

The problem with randomness is that you never can tell.

Alun Harford
Zytan - 16 May 2007 17:06 GMT
> Here are some random numbers:
>
[quoted text clipped - 3 lines]
> 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
> 5, 5, 5.

No, you copied and pasted.  They are completely not random!  ;)  But,
I get your point.

My real question is:  Is C#'s Random() better than C's rand()?
(because C's rand() showed patterns.)

Zytan
Jon Davis - 16 May 2007 17:16 GMT
> The problem with randomness is that you never can tell.

I'm feeling warm and fuzzy when I say, statistically fuzzy is how we should
all feel.

Jon
Jesse Houwing - 20 May 2007 23:33 GMT
* Alun Harford wrote, On 16-5-2007 16:15:
>> Anyone do any tests on it?  I would assume it has improved since C's
>> rand(), but who knows.  For some reason, and it could just be
[quoted text clipped - 13 lines]
>
> Alun Harford

That reminds me of the following Comic on XKCD:

http://imgs.xkcd.com/comics/random_number.png

Fesse
rossum - 16 May 2007 20:31 GMT
>Anyone do any tests on it?  I would assume it has improved since C's
>rand(), but who knows.  For some reason, and it could just be
[quoted text clipped - 3 lines]
>
>Zytan
Have you googled for the Diehard tests?

rossum
Zytan - 21 May 2007 15:56 GMT
> Have you googled for the Diehard tests?

No, I haven't.

Zytan
Carl Daniel [VC++ MVP] - 17 May 2007 20:39 GMT
> Anyone do any tests on it?  I would assume it has improved since C's
> rand(), but who knows.  For some reason, and it could just be
> coincidence, I seem to see patterns.  But even a crappy rand()
> function should be good enough to avoid that, so i may be seeing
> things.

It's likely that .NET's Random is almost exactly as good as the C rand()
function - AFIAK, they're both simple linear congruential generators.
They're fast, but not particularly random.

Without getting into crypto generators (which are horrifically slow,
compared to an LCG), there are a number of RNG algorithms that can do a lot
better than a simple LCG.  Consult your favorite algorithms book (Sedgewick,
Knuth, Rivest, etc) for details.

-cd
Arne Vajhøj - 19 May 2007 23:19 GMT
> Anyone do any tests on it?  I would assume it has improved since C's
> rand(), but who knows.  For some reason, and it could just be
> coincidence, I seem to see patterns.  But even a crappy rand()
> function should be good enough to avoid that, so i may be seeing
> things.

.NET Random uses "Donald E. Knuth's subtractive random number
generator algorithm" says the docs.

Decompile code indicates that it uses an array of size 56.

It seems to be a special case of modern MRG with coefficients of 1.

Based on that:
- Knuth is who he is
- MRG's are generally considered good
- MS choose that algorithm
then I am sure that it is better than the standard C rand()
based on simple LCG's.

So check if there is a problem and if yes then check your code.

You can do simple tests by tabulating high bits and low bits
in 1D, 2D etc..

Arne
Zytan - 21 May 2007 15:58 GMT
> .NET Random uses "Donald E. Knuth's subtractive random number
> generator algorithm" says the docs.
[quoted text clipped - 14 lines]
> You can do simple tests by tabulating high bits and low bits
> in 1D, 2D etc..

Ok, thanks, Arne.  From our simple tests, it is better than C's
rand().

Zytan

Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.