YAP Prolog random's lack of randomness

246 Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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

4
On

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.