There's no need/point to reseed every time you ask for a random
number, arguably it could decrease your actual randomness
(IANACryptographer). I'd go one further and add an `on_load` attribute
to your module, and initialise the seed there. on_load specifies a
function to be called only when your module is loaded the first time,
or later if you do hot-code reloading. So, its more or less automatic.
I've got no computer atm, so something like this should work:
defmodule Randomise do
@on_load :reseed_generator
def reseed_generator do
:random.seed(:os.timestamp())
end
def random(number) do
:random.uniform(number)
end
end
Look at
http://elixir-lang.org/docs/stable/Module.html and
http://www.erlang.org/doc/reference_manual/code_loading.html for more
info.
A+
Dave
On 16 January 2014 09:09, Riza Fahmi <
riza...@gmail.com> wrote:
> Oh, ok I didn't know that. Thanks for figuring out for me :)
>
> This is the revision using seed.
>
>
>
>
> defmodule Randomize do
> def random(number) do
> :random.seed(:erlang.now())
> :random.uniform(number)
> end
> end
>
>
>
> IO.inspect Randomize.random(10)
>
>
>
> On Thu, Jan 16, 2014 at 2:41 PM, José Valim
> <
jose....@plataformatec.com.br> wrote:
>>
>> You need to give it a seed. Check the documentation for the seed function
>> here:
>>
>>
http://www.erlang.org/doc/man/random.html
>>
>> Otherwise it uses a default seed (if I remember correctly).
>>
>>
>>
>> José Valim
>>
www.plataformatec.com.br
>> Skype: jv.ptec
>> Founder and Lead Developer
>>
>>
>> On Thu, Jan 16, 2014 at 8:34 AM, Riza Fahmi <
riza...@gmail.com> wrote:
>>>
>>> Hi all,
>>>
>>> I'm trying to use erlang module random in elixir script. But everytime I
>>> run it (elixir random.exs), it always return the same number. Trying it on
>>> REPL is normal, it randomize. Am I doing it wrong? This is the code:
>>>
>>>
>>>
>>> defmodule Randomize do
>>> def random(number) do
>>>
>>> :random.uniform(number)
>>>
>>>
>>>
>>>
>>>
>>> end
>>> end
>>>
>>>
>>>
>>>
>>>
>>>
>>> IO.inspect Randomize.random(10)
>>>
>>>
>>>
>>>
>>>
>>>
>>>
https://gist.github.com/rizafahmi/8451050#file-random
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>