Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erlang - Random Number Generator

I am using the following to generate a near random number.

3> erlang:ref_to_list(make_ref()).

"#Ref<0.0.0.36>"

What I want is 00036

Well it was what I had been informed I could do in a previous post. It occurred to me that it is not so easy to extract the numbers from make ref.

Can anyone show how it is easily done, or possibly recommend another solution.

Keep in mind that using random:seed() is not random when called within the same few nano seconds.

Regards

like image 597
BAR Avatar asked Nov 29 '22 04:11

BAR


1 Answers

Note: from OTP 18 erlang:now/0 and random module are deprecated, and OTP 20 will remove the random module. See Time and Time Correction in Erlang for the further details. Also, you no longer need to do the per-process seeding if you use rand:uniform/0. The following is left as is for reference.


The problem is that you are using random incorrectly. random:seed/0 will seed the random number generator with the very same seed always. This is not good for what you want. Rather, you can use random:seed(erlang:now()) to seed it with another number, namely the current time.

"What happens if two calls come very close?" you may ask. Well, the Erlang guys thought about this, so now/0 is guaranteed to always return increasing numbers:

Returns the tuple {MegaSecs, Secs, MicroSecs} which is the elapsed time since 00:00 GMT, January 1, 1970 (zero hour) on the assumption that the underlying OS supports this. Otherwise, some other point in time is chosen. It is also guaranteed that subse‐ quent calls to this BIF returns continuously increasing values. Hence, the return value from now() can be used to generate unique time-stamps, and if it is called in a tight loop on a fast machine the time of the node can become skewed.

(emphasis mine)

Also note that the random PRNG is per-process, so you should always start your process up with a seeder call:

init([..]) ->
  random:seed(erlang:now()),
  [..]
  {ok, #state { [..] }}.

Using references for this is perhaps possible, but I don't think it is a viable one. The solution goes over erlang:ref_to_list/1 and it is not pretty.

like image 94
I GIVE CRAP ANSWERS Avatar answered Dec 04 '22 10:12

I GIVE CRAP ANSWERS