Merge pull request #2690 from notoria/next

Add '$random_integer'/3
This commit is contained in:
Mark Thom
2024-12-13 21:38:32 -07:00
committed by GitHub
6 changed files with 78 additions and 23 deletions

View File

@@ -15,16 +15,14 @@ the random seed. This makes everything completely reproducible.
% Succeeds with probability 0.5.
maybe :- '$maybe'.
% The higher the precision, the slower it gets.
random_number_precision(64).
%% random(-R).
%
% Generates a random floating number between 0 (inclusive) and 1 (exclusive).
random(R) :-
var(R),
random_number_precision(N),
rnd(N, R).
N is 2^50,
'$random_integer'(0, N, K),
R is K/N.
%% random_integer(+Lower, +Upper, -R).
%
@@ -41,25 +39,10 @@ random_integer(Lower, Upper, R) :-
type_error(integer, Lower, random_integer/3)
; \+ integer(Upper) ->
type_error(integer, Upper, random_integer/3)
; Upper > Lower,
random(R0),
R is floor((Upper - Lower) * R0 + Lower)
; Lower < Upper,
'$random_integer'(Lower, Upper, R)
).
rnd(N, R) :-
rnd_(N, 0, R).
rnd_(0, R, R) :- !.
rnd_(N, R0, R) :-
maybe,
!,
N1 is N - 1,
rnd_(N1, R0, R).
rnd_(N, R0, R) :-
N1 is N - 1,
R1 is R0 + 1.0 / 2.0 ^ N,
rnd_(N1, R1, R).
%% set_random(+Seed).
%
% Sets a seed that will be used for subsequent random generations in this library.