Random Numbers in Prolog

Here’s the translation of the Go random numbers example to Prolog:

Our program will demonstrate generating random numbers in Prolog. Here’s the full source code:

:- use_module(library(random)).

main :-
    % Generate random integers between 0 and 99
    random_between(0, 99, R1),
    random_between(0, 99, R2),
    format('~w,~w~n', [R1, R2]),

    % Generate a random float between 0.0 and 1.0
    random(F),
    format('~f~n', [F]),

    % Generate random floats between 5.0 and 10.0
    random(0.0, 1.0, F1),
    random(0.0, 1.0, F2),
    F1_scaled is F1 * 5 + 5,
    F2_scaled is F2 * 5 + 5,
    format('~f,~f~n', [F1_scaled, F2_scaled]),

    % Set a known seed for reproducible results
    set_random(seed(42)),
    random_between(0, 99, R3),
    random_between(0, 99, R4),
    format('~w,~w~n', [R3, R4]),

    % Reset the seed to get the same sequence
    set_random(seed(42)),
    random_between(0, 99, R5),
    random_between(0, 99, R6),
    format('~w,~w~n', [R5, R6]).

In Prolog, we use the random library to generate random numbers. Let’s break down the code:

  1. We use random_between/3 to generate random integers between 0 and 99.

  2. random/1 generates a random float between 0.0 and 1.0.

  3. To generate random floats between 5.0 and 10.0, we use random/3 to get a float between 0.0 and 1.0, then scale and shift it.

  4. Prolog doesn’t have a built-in PCG (Permuted Congruential Generator), but we can set a known seed using set_random/1 for reproducible results.

  5. We demonstrate that resetting the seed produces the same sequence of random numbers.

To run the program, save it as random_numbers.pl and use the Prolog interpreter:

$ swipl -q -s random_numbers.pl -g main -t halt
68,56
0.809023
5.840125,6.937056
94,49
94,49

Note that the actual numbers generated may be different when you run the sample, except for the last two lines which should be identical due to the seed reset.

Prolog’s random number generation capabilities are provided by the random library. Consult the SWI-Prolog documentation for more details on available predicates for random number generation.