Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erlang - Random Number gen with Makeref

I am trying to generate a random enough number quickly.

Right Now I am using the following:

uniqueID() ->   C = random:uniform(9999) ,   %%%DO SPEED TEST
    random:seed(C,random:uniform(99),random:uniform(99)),
    {_, {H, Min, S}}  = calendar:universal_time(),
    {A, B} = statistics(wall_clock),
    (A*B) +((H + C + Min) * S).

It takes too long compared to something like make_ref().

6> make_ref().
#Ref<0.0.0.74>

How can I take the unique ref and parse it to become an integer?

such as 00074

Thanks for the help.

like image 288
BAR Avatar asked Feb 10 '11 20:02

BAR


People also ask

How do you generate a random number in Erlang?

To generate a 1000-element list with random numbers between 1 and 10: [rand:uniform(10) || _ <- lists:seq(1, 1000)]. Change 10 and 1000 to appropriate numbers. If you omit the 10 from from the rand:uniform call, you'll get a random floating point number between 0.0 and 1.0.

How does Groovy generate random numbers?

Groovy - random() The method is used to generate a random number between 0.0 and 1.0. The range is: 0.0 =< Math. random < 1.0. Different ranges can be achieved by using arithmetic.


2 Answers

Are you really sure you want to use erlang:make_ref/0 for unique numbers? Refs are only unique for one launch of one erlang vm - they are repeatable, predictable, and make lousy unique identifiers if you plan to use them for anything other than tags in erlang messages to match up requests and replies.

You could do it by formatting the ref as a string (erlang:ref_to_list/1) and then parsing that.

However, I think the best idea would be to use crypto:rand_bytes/1 to get yourself an N byte binary of random bytes, or crypto:rand_uniform/2 if you need a random integer in some range. This method at least gives you some guarantees as to the quality of the random integers you produce (see the openssl rand_bytes documentation).

like image 111
archaelus Avatar answered Sep 30 '22 16:09

archaelus


{A,B,C} = now(), A * 1000000000000 + B * 1000000 + C.

like image 22
probsolver Avatar answered Sep 30 '22 16:09

probsolver