LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   using /dev/random to output random numbers on a text file (https://www.linuxquestions.org/questions/programming-9/using-dev-random-to-output-random-numbers-on-a-text-file-542376/)

guguma 04-01-2007 10:29 AM

using /dev/random to output random numbers on a text file
 
Hello and good days,

First of all this is not a programming class homework or whatever so please do not humiliate me with that kind of approach.

I have searced around and I found that /dev/random can create an "entropy pool" from keyboard, mouse, or CPU interrupts and then these random interrupts can be used to create a set of true random numbers.

I need to create a set of random numbers (about 10.000) between 0 and 1. And I really need them to be uniformly distributed, then I saw all the things about /dev/random and hoped that I can use it to do this. I can code in C language but I am not that much of an expert so I have no idea how to access this /dev/random to accomplish what I have hoped.

So could anyone please help me on this, any kind of material, link (maybe around some dark corners of te web there is a page that slipped my attention) or knowledge is appreciated.

Thanks in advance.

acid_kewpie 04-01-2007 01:37 PM

just use fopen() like any other file for reading.

Mara 04-01-2007 01:38 PM

The numbers between 0 and 1 are not integers. That makes the whole problem non-trivial. The first issue is what format you want them to have. In standard C you have float and double, but you probably already know that you can't get all possible values using float or double type. So first think about the precision you need.

Then you just need to get a number of bits from /dev/random and scale them to what you want. For instance, if you want a value between 0.00 and 1.00 (with two digits) you can get one byte and convert the 256 possible values to 99 you want. You may make the scale linear to make things simplier, so for instance (the issue is that 256 divided by 99 is not an integer) 0x02 will be 0.01 and 0xfe - 0.99. You can also write a table with ranges to make things simplier.

syg00 04-01-2007 02:25 PM

And if you are generating 10,000 you might want to look at /dev/urandom as it's non-blocking.

nmh+linuxquestions.o 04-02-2007 01:42 PM

Though a bit more complicated, I think it is usually regarded as a better idea to seed a prng from /dev/rand and then use that to generate a series of random numbers (as opposed to pulling them from /dev/rand). One option that should provide random, uniformly distributed, etc, etc, etc.. numbers is the Mersenne twister:
http://en.wikipedia.org/wiki/Mersenne_twister

You can write your own implimentation, or use one of the existing ones:
http://www.gnu.org/software/gsl/
http://www.cs.hmc.edu/~geoff/mtwist.html


All times are GMT -5. The time now is 11:36 AM.