4

When executing the following Prolog program with YAP, the output is always the same, namely the integer 233.

:- use_module(library(random)).    
x:- random(1,1000,X), writeln(X).

For instance, if I execute the following bash script, the output is always the same integer (233).

for k in `seq 0`
do
  yap -l test.pl << %
  x.
%
done

If I repeat this procedure using swipl, then the output is different each time, i.e random.

Can anyone explain this?

repeat
  • 18,496
  • 4
  • 54
  • 166
S0rin
  • 1,283
  • 1
  • 10
  • 22

2 Answers2

4

First things first!

For many good reasons (reproducibility of past results being the most important one) computer programs do not work with actual random numbers, but with pseudo random numbers.

PRNGs are fully deterministic functions that, given the same internal state (a.k.a. "seed") as initialization, produce exactly the same sequence of numbers (from now until eternity).

Quick fix: find yourself a suitable seed (date, time, phase of the moon, ...) and explicitly initialize the PRNG with that seed. Record the seed so you can later deterministically re-run past experiments.

repeat
  • 18,496
  • 4
  • 54
  • 166
  • 1
    The most important reason is not "reproducibility" of past results, but due to the fact that you cannot find a source of random numbers with the hardware provided with current computers. – gusbro Oct 08 '15 at 18:11
  • 3
    @gusbro. I disagree. In fact, several options have always been available, but they are only used when real randomness is *a must*; typically they tap into some stochastic physical process using sensor data (see serverfault.com/questions/214605/gpg-not-enough-entropy); a few years ago, Intel 64 processors got HW-support accessible by using the instruction-set extension "RdRand" (see https://en.m.wikipedia.org/wiki/RdRand). – repeat Oct 08 '15 at 21:56
  • 1
    Some years ago CPUs didn't have those instructions, and a typical computer didn't have those sensors (soundcard, high frequency counter, etc are not good sources to sample from). – gusbro Oct 08 '15 at 22:06
  • 1
    @gusbro. Factually correct, from a historical perspective! The point I originally tried to make, however, is this: even if "true" randomness is available *for free*, the non-determinism it enables is only an asset for a small number of select applications like the generation of public keys in cryptography, Monte Carlo style simulations, incomplete massively parallel search space exploration (without the need for dynamic partitioning and coordination for the avoidance of duplicate work). – repeat Oct 09 '15 at 06:09
2

usually, random generators require something like set_seed(SomeReallyRandomValue) call, in C was often used seed(time(0)). So, I guess

datime(datime(_Year, _Month, _DayOfTheMonth, _Hour, Minute, Second)),
X is Minute * Second,Y=X,Z=X,
setrand(rand(X,Y,Z)),

could work

CapelliC
  • 59,646
  • 5
  • 47
  • 90