# VBForums CodeBank > CodeBank - Visual Basic .NET >  "True Random" Number Generator

## Phill64

After concern and debate of the Random Class in .NET and knowing from experience the vb6 random was terrible, i found it necessary to create this, i will be using this myself for my next mp3 player.

This DOES NOT use the original Random class in any way, shape or form, i have seen examples of "better" random classes which try to extend the original, which, is practically impossible.

This class is a complete built solution, it uses 4 factors most likely to change:

System Timer
System Memory (RAM)
CPU Usage
Mouse Position

Why is this class "more random" than the pre-packaged one you ask?
Because classic random uses just the timer as a seed, and a mathematical pattern to generate from then on, so it will ALWAYS create a pattern

Whereas, this class only follows patterns for a limited time(long enough for new data to come in) and the fact it uses RAM and the Mouse Position means it is effected in a way unknown to the system.

The system clock spins circles, so it will of course create a pattern.
a user moving their mouse is COMLETELY unpredictable.
RAM is effected continuously in ways that can never be predicted(within reason)
CPU performance is effected by everything running and even the weather!thus the CPU can also never be accurately predicted


How did I test the results? (demo is attached)

by creating 2 classes of the classic Random, and 2 classes of TrueRandom
then making all 4 create a list of random numbers
classic random generated 2 IDENTICAL lists every time i tested
whereas the 2 TrueRandom classes would create 2 different lists

Conclusion:
multiple of this class, created under all the same conditions returns different results,
that is truely random.


Now that's the background out of the way, below is a screenshot of the test program, the class file, and the source to the demo program.

Was this useful? please comment or rate

----------


## jmcilhinney

That sure does seem random.  I guess for a situation that really does require true random numbers then something like this is the way to go, but Integer.MaxValue different psuedo-random sequences created from a seed that is not directly controlled by the user or developer would be random enough for all but the most demanding cases.  I do have a small criticism of your code too.  The use of non-descriptive variable names means you need to study the code for a while to determine exactly what it is doing.  More descriptive variable names would make it a lot easier to understand.  Otherwise, most goodly and excellentful.  :Smilie:

----------


## Phill64

> That sure does seem random.  I guess for a situation that really does require true random numbers then something like this is the way to go, but Integer.MaxValue different psuedo-random sequences created from a seed that is not directly controlled by the user or developer would be random enough for all but the most demanding cases.  I do have a small criticism of your code too.  The use of non-descriptive variable names means you need to study the code for a while to determine exactly what it is doing.  More descriptive variable names would make it a lot easier to understand.  Otherwise, most goodly and excellentful.


Thanks alot Jm,

i wouldn't say most demanding cases, if randomness is a main part of your application, as i mentioned an mp3 player, it can be a big issue. Of course when random is only used a small amount of times it is no problem to use stock standard methods.

Apologies for the cryptic variable names, i may review that and repost, i should have cleaned it up before i posted it

----------


## jmcilhinney

I assume you mean for a random play feature.  But if you seed a Random object with CInt(Date.Now.Ticks Mod Integer.MaxValue) then the likelihood of you ever getting the same sequence twice is miniscule.  Not as miniscule as using your method of course, but still very small.  I can't imagine using the random play function on a media player even close to Integer.MaxValue (2147483647) times.

----------


## Phill64

> I assume you mean for a random play feature.  But if you seed a Random object with CInt(Date.Now.Ticks Mod Integer.MaxValue) then the likelihood of you ever getting the same sequence twice is miniscule.  Not as miniscule as using your method of course, but still very small.  I can't imagine using the random play function on a media player even close to Integer.MaxValue (2147483647) times.


Jm, i can assure you that this is not true, as i still use my vb6 player today.. which uses the standard randomize function with the timer, and i get all the same songs, all the time, often in the same order, i am always changing the song, i put up with it for now because i hant got around to making my new one. It's a great event when my collection size changes, as then the songs that popup do to. It is because it's large scale, and happening all the time, as i mentioned, it is just a pattern, a complex "random" algorithm is used to generate the next number in the pattern from the seed, it will always be the same. The only advantage i can see to the classic method is speed.

btw, i updated the files with better variable names

----------


## meboz

hey there,

this thread caught my attention cos im interested in the randomness of the random class.

if you adjust your code behind the form to look something like this.


VB Code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    ListBox1.Items.Clear()
    ListBox2.Items.Clear()
    ListBox3.Items.Clear()
    ListBox4.Items.Clear()
     Call FillListBox(Me.ListBox1)
    Call FillListBox(Me.ListBox2)
    Call FillListBox(Me.ListBox3)
    Call FillListBox(Me.ListBox4)
 End Sub
     Private Sub FillListBox(ByVal listbox As ListBox)
        For i As Int32 = 0 To 100
            listbox.Items.Add(Rand.GetNext(0, 1000))
        Next
    End Sub

then the numbers in the listboxes using the .Net random class, are different.

I would seem that within each run of a loop, if you use the Next function call, it returns the same number, so it has* not* truely regenerated a new random number, which it does once it loops.

Perhaps it is the way in which consumers implement the random class that is the issue, rather than the class itself.

By the way, i think your TrueRandom class is very well thought out nonetheless, and I willl endeavour to use it when I have to generate random numbers, given that less thought must go into worrying about how I call a new random number

----------


## Phill64

I'm not sure what you're trying to say here,
your example uses "Rand.GetNext" which is the TrueRandom class, not the Random class, "ORand.Next" is the original random class.




> Perhaps it is the way in which consumers implement the random class that is the issue, rather than the class itself.


that is definetly a valid issue, the original random class likes to be recreated every now and again so its current pattern may be dropped for a new one, which alot of people are probably not aware, but on the other hand doing this at a time interval or frequently will also be a problem.

Of course back to the point of this project, it depends "how random" you need things  to be, in most cases the original class will do nicely. A Custom class is suited for programs which revolve around the use of alot of random numbers




> By the way, i think your TrueRandom class is very well thought out nonetheless, and I willl endeavour to use it when I have to generate random numbers, given that less thought must go into worrying about how I call a new random number


Thanks alot  :Big Grin:

----------


## wossname

Not to mention that all this extra object code on top of the framework is rather pointless when there is a Cryptographically-strong randomizer in the security namespace of the framework anyway.

*ahem* Sorry to piddle all over this splendidly roaring bonfire.

----------


## meboz

your right phill, my mistake.

----------


## Phill64

> Not to mention that all this extra object code on top of the framework is rather pointless when there is a Cryptographically-strong randomizer in the security namespace of the framework anyway.
> 
> *ahem* Sorry to piddle all over this splendidly roaring bonfire.


That class uses the exact same method as the other random class, and does not create a number, it creates random bytes

from the help topic about that class



> The chosen numbers are not completely random because a definite mathematical algorithm is used to select them, but they are sufficiently random for practical purposes.


Sorry to waste your piddle.

----------


## wossname

> That class uses the exact same method as the other random class, and does not create a number, it creates random bytes


Uhh no it doesn't, and there is no difference between a random number and a random byte.

I have just tested 10 instances of the cryptographically strong RNG and it never produces duplicate lists.

It can be easily used to generate random 32bit integers with some bit manipulation.  It's optimised for speed too.

----------


## Phill64

hmmm,

it appears you're right, that class also creates two different sequences of numbers with two instances.

It's odd that help doesn't mention much about it, i guess it's for security reasons.

You'd still need to make your own class to get the number between x and y operation instead of 0-255 in byte form, So i don't think my class is unjustified, although i admit in most cases strong randomness is used with byte operations. 

Whatever your opinion this way was still alot more fun, and is educational to those who read it, regarding the construction of random numbers in a logical environment.

----------


## wossname

Certainly not bereft of educational value I agree.  :Thumb:

----------


## zaza

If I wanted to generate random numbers for a big simulation using this, would I have to sit up all night moving the mouse around?

 :Smilie:

----------


## Phill64

> If I wanted to generate random numbers for a big simulation using this, would I have to sit up all night moving the mouse around?


no, mouse xy is only 1 factor, and a minor one, for that very reason, it is the slowest moving variable, the mouse spends alot of its time sitting still.

----------


## Mandelbrot

It's not too much trouble to simply generate random bytes then string them together and convert them to Int64, Int32 or Int16 (blah)...

Then, if you want a float, simply divide the result by ... whatever you want, really - even another randomly generated byte series.  Alternatively, just divide 1 by your byte series.

----------


## wossname

Or rather (random byte / 256) to get a float in the range 0-1 but the resolution would be very poor.

Probably the fastest way to get a random int32 out of the cryptographically safe RNG is to write a whole bunch of bytes to a memory stream and then go back to the start and use ReadInt() to fetch them out in chunks of 32bits.  This would be pretty fast.

I'm currently looking into RNG's in assembly language which is why I came back to this thread  :Smilie:

----------


## Mandelbrot

LOL!  Slipping back to assembly!  Defeats the OOP objective, slightly  :Wink: .  It will be incredibly fast, though.

Seriously, though, wouldn't C++ be fast enough, and still enable you to retain OOP standards...

----------


## wossname

OOP is not everything you know.  Nobody would seriously code a fullscale app in ASM these days for that exact reason, but ASM is very useful for spot-tuning an app.  Write a particularly complex algorithm in ASM and it'll thrash any OOP language.  ASM is brilliant.

Some of the stronger pseudo random generators are pretty complex and are great candidates for Assembly treatment.  Also things like checksumming are equally logic intensive.

----------


## Mandelbrot

No - I don't deny it.  I used a bit of M68K at college, but would rather write it in C++, which, while not as fast as asm is still a viable option.

----------


## FauxQuixote

One big flaw I can see is that you cannot seed your generator to get an expected series of numbers. Your generator is useless for the most necessary use of random number generators... hashing and encryption.
And if it's not for security purposes, how "random" does it really need to be?

----------


## Phill64

You havn't paid attention have you, seeding is what prevent things actually being random, the idea of this class was specifically not to seed. And yes, it can be used for security, to use random generation in security the idea is to create a random array of numbers or bytes, which is then used as an encryption key, if you use a seed, bah! your big list of numbers is absolutely useless, as all they need is that 1 seed number, use the same random algorithm with different seeds until they break your code. That means your level of encryption is limited to a Double, 2bytes

the best encryption algorithms use the true number methods, more ellaborate than this, i have heard of one that uses light sensors to read a lava lamp and generates numbers from that, unpredictable. Another example is an accounting package which asks the user to move their mouse around alot and records that as their random encryption key. You are absolutely wrong.

----------


## FauxQuixote

I was thinking more in terms of hashing... where a value must produce the same hash every time. How is this accomplished with truly random numbers?

----------


## Phill64

It can't be, but hashing isn't supposed to be random, it's supposed to be a math system (which yes, the standard random class is a math system) so i don't doubt you have made a hash with it before

I am not going to dissagree that seeding is a good ability, i use it to make things happen "randomly" on network games, so the host just needs to send the seed at the start to have the same result on both programs. But that's the point, it's not actually random, there are ups and downs to both, just like anything.

----------


## Phill64

After a recent thread i have decided to slightly restructure this class, so that a .GetDouble method exists to return the 0-1 value, and .GetNext() returns a random integer and .GetNext(min,max) performs the same as it used to, this allows for the creation of any kind of number beyond integer to be made with a simple multiplication and rounding of the .GetDouble method, a long could be created for example.

The new class is attached

----------


## Maven

> You havn't paid attention have you, seeding is what prevent things actually being random, the idea of this class was specifically not to seed. And yes, it can be used for security, to use random generation in security the idea is to create a random array of numbers or bytes, which is then used as an encryption key, if you use a seed, bah! your big list of numbers is absolutely useless, as all they need is that 1 seed number, use the same random algorithm with different seeds until they break your code. That means your level of encryption is limited to a Double, 2bytes
> 
> the best encryption algorithms use the true number methods, more ellaborate than this, i have heard of one that uses light sensors to read a lava lamp and generates numbers from that, unpredictable. Another example is an accounting package which asks the user to move their mouse around alot and records that as their random encryption key. You are absolutely wrong.


Missconceptions flowing in this thread:
1. A computer is a deterministic machine and any number generated by it will also be deterministic, in other words, pseudo-random. 
2. A random number generator for crpytographic algorithms, like the one microsoft has in it's API (more specificly cryptoapi, wraped by .net)  is about as random as your going to get a computer to generate. In fact, you'll find it may actually access the INTEL hardware random number generator, which makes software ones obsolete. =)
3. I shall quote someone else:



> Perhaps the simplest example is a linear congruential sequence, one of the most popular types of random number generators, where there is no obvious dependence between seeds and outputs. Unfortunately the graph of any such sequence will, in a high enough dimension, show up as a regular lattice. Mathematically this lattice corresponds to structure which is notoriously easy for cryptanalysts to exploit. More complicated generators have more complicated structure, which is why they make interesting pictures--- but a cryptographically strong sequence will have no computable structure at all


4. If you want to find a true random number then you have to look to places like radioactive decay. Which means that your going to have to find and buy a machine designed to do just that or build your own. Not a very effective solution for the avg joe.

----------


## Phill64

oh dear, not another.

I could argue that your radioactive machine will be deterministic, god made nature the same way man made computers, we simply DON'T KNOW how nature works... so... it APPEARS random.

In the common PC, there are so many factors that we DON'T KNOW that when you combine them it APPEARS random. The Point is that it can't be predicted by a human.. the standard random class uses a seed value to make a list of numbers, get the key you can predict every single number from then on... Could you take 5 numbers created by my class and predict the next 10? you could with the normal random class, after u go through all the seed values until you find the one that returns those first 5 numbers...

And yes, it has already been pointed out the crypto class performs exactly that of my class. As for the hardware thing.. just because it comes from low level, what makes you think it works better? it may very well just take the current system clock  :Wink: 

perhaps i shouldn't have used the word True (even though the title is in quotation to avoid this very argument)... because if you want to get all nitty gritty technical about base patterns and whatnot, then unless you're god, there is no such thing.. if it can't be predicted, it's truely random. Eventually some other scientist will find a reason that decaying radioactive material is not random because finally they understand it, and whatever the next least understood thing is will be considered random.

----------


## Maven

[QUOTE=Phill64]oh dear, not another.





> I could argue that your radioactive machine will be deterministic, god made nature the same way man made computers, we simply DON'T KNOW how nature works... so... it APPEARS random.


According to quantum physics, we live in a indeterministic universe.




> In the common PC, there are so many factors that we DON'T KNOW that when you combine them it APPEARS random. The Point is that it can't be predicted by a human.. the standard random class uses a seed value to make a list of numbers, get the key you can predict every single number from then on... Could you take 5 numbers created by my class and predict the next 10? you could with the normal random class, after u go through all the seed values until you find the one that returns those first 5 numbers...


The standard random class is ment to be used for general purpose. Card games, scientitic experiments and the like. For example if you was going to do an experiment, you'll want to re-run with the same conditions, IE: same series of numbers. Now when it comes to proecting my credit card number, I wouldn't use it or yours because neither one is cryptographically secure. 




> And yes, it has already been pointed out the crypto class performs exactly that of my class. As for the hardware thing.. just because it comes from low level, what makes you think it works better? it may very well just take the current system clock


No it does not, Read #3.

The crypto class uses a seed though they make their best efforts at making it as random as they can. 
examples:




> The system time. 
> Any high-precision clocks that exist on the system board and peripherals. 
> The cursor or mouse pointer location. 
> Any accumulated physical state information devices such as in keyboard input buffers, I/O service queues, and video drivers. 
> The number of tasks in the OS scheduling queue, their task identifiers, or their code base addresses and sizes. 
> Data from the application, passed into the CryptGenRandom function and passed on to CPGenRandom as the input bytes in pbBuffer.





> perhaps i shouldn't have used the word True (even though the title is in quotation to avoid this very argument)... because if you want to get all nitty gritty technical about base patterns and whatnot, then unless you're god, there is no such thing.. if it can't be predicted, it's truely random. Eventually some other scientist will find a reason that decaying radioactive material is not random because finally they understand it, and whatever the next least understood thing is will be considered random.


That is the actually definition of truely random: "Can't be predicted". Though people like to have that mathematically proven.

----------


## Phill64

I know the crypto class does this, because it behaves the same as mine does.. which uses the same principle, so under what basis do you call mine not secure? 

I was actually talking about your Intel statement which you say makes "all software" methods "obsolete"

wouldn't that make the .net's crypto method "obsolete"?

Sorry But I don't think you are coming to any kind of point here, but more or less just ranting on about the crypto class which has already been concluded in this thread

----------


## Phill64

Alright, 

Since i am fed up with being harrased about this class, i have gone ahead and made a new one which uses the security namespace random class as a back-end and published it in a new thread.

The thread is located here: http://www.vbforums.com/showthread.php?t=390737

----------


## RobDog888

Thread Closed at users request.

----------

