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:
In Prolog, we use the random
library to generate random numbers. Let’s break down the code:
We use
random_between/3
to generate random integers between 0 and 99.random/1
generates a random float between 0.0 and 1.0.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.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.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:
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.