| Author |
Message |
< Erlang ~ random:uniform acting weird |
| Amadeus |
Posted: Mon Nov 23, 2009 12:12 pm |
|
|
|
Joined: 23 Nov 2009
Posts: 4
|
Hey!
Was looking for a way to generate random numbers in Erlang and found a tutorial here on Trapexit, showing how to use random:uniform(N), to get a random number number between 1 and N.
However, everytime I use it, it returns 1 the first time. After the first time it randomizes "correct", but the first time will always return 1, which I don't think is correct behavior.
It happens every single time for me, and also for another friend that I asked to try it. Anyone know about this? And what I could use instead/or how I could fix this?
Cheers!
Amadeus |
|
|
| Back to top |
|
| Karalabe |
Posted: Mon Nov 23, 2009 12:36 pm |
|
|
|
User
Joined: 03 Jul 2009
Posts: 11
|
Hi,
Erlang's (and every other programming languages') random number generator is only pseudo random. Meaning that the random number sequence is based on an initial seed value. As with other languages, if you don't set a particular seed, the system takes a default one (which is probably the same over multiple runs). To solve your issue, seed the random number generator with the current time.
{A1, A2, A3} = now().
random:seed(A1, A2, A3).
(Strange though that the documentation states that random:seed(now()) should also works, but it doesn't... oh well).
Have a nice day,
Peter |
|
|
| Back to top |
|
| Amadeus |
Posted: Mon Nov 23, 2009 12:51 pm |
|
|
|
Joined: 23 Nov 2009
Posts: 4
|
Wicked! Thanks a lot, didn't know that.  |
|
|
| Back to top |
|
| Allan |
Posted: Mon Nov 23, 2009 2:20 pm |
|
|
|
User
Joined: 29 Jun 2009
Posts: 30
|
| Depending on what you want to use the random numbers for, crypto:rand_bytes/1 or crypto:rand_uniform/2 may be much better choices... |
|
|
| Back to top |
|
| rvirding |
Posted: Tue Nov 24, 2009 7:20 am |
|
|
|
User
Joined: 30 Aug 2006
Posts: 452
Location: Stockholm, Sweden
|
Allan wrote: Depending on what you want to use the random numbers for, crypto:rand_bytes/1 or crypto:rand_uniform/2 may be much better choices...
Yes, you definitely NOT use the random module for cryptographic work, it is not suitable for that. For simulation and such though it works quite well. |
|
|
| Back to top |
|
| Amadeus |
Posted: Tue Nov 24, 2009 12:12 pm |
|
|
|
Joined: 23 Nov 2009
Posts: 4
|
Just updating to say it works perfectly, thanks again!
I use the crypto to handle SHA hashing, but random:uniform was enough for what I wanted to do, which was select a random number from 1 to the length of a list to select a random ID in it.
Cheers for taking your time! |
|
|
| Back to top |
|
|
|