next_below Interface

public interface next_below

Draw a uniform integer in [0, n) by rejection sampling.

The naive mod(next(), n) is biased whenever n does not divide the generator’s period: the first 2**64 mod n residues each get one extra preimage, so for large n some outcomes are measurably more likely. Instead a mask of the smallest 2**k - 1 at least n - 1 is applied to a fresh 64-bit word and values at or above n are rejected and redrawn. Every accepted value has exactly one preimage per draw, so the result is exactly uniform. The acceptance probability is above 1/2, so the expected number of draws is below 2 and the loop terminates with probability one.

n == 1 returns 0 without consuming a draw. n <= 0 is a usage error: it returns 0 and, if error is present, sets ERROR_VALIDATION.

Calls

interface~~next_below~~CallsGraph interface~next_below next_below proc~pcg32_next_below pcg32_next_below interface~next_below->proc~pcg32_next_below proc~splitmix64_next_below splitmix64_next_below interface~next_below->proc~splitmix64_next_below proc~error_set error_t%error_set proc~pcg32_next_below->proc~error_set proc~pcg32_next_u64 pcg32_t%pcg32_next_u64 proc~pcg32_next_below->proc~pcg32_next_u64 proc~rejection_mask rejection_mask proc~pcg32_next_below->proc~rejection_mask proc~splitmix64_next_below->proc~error_set proc~splitmix64_next_below->proc~rejection_mask proc~splitmix64_next_u64 splitmix64_t%splitmix64_next_u64 proc~splitmix64_next_below->proc~splitmix64_next_u64 proc~pcg32_step pcg32_step proc~pcg32_next_u64->proc~pcg32_step proc~splitmix64_next splitmix64_t%splitmix64_next proc~splitmix64_next_u64->proc~splitmix64_next proc~rotate_right32 rotate_right32 proc~pcg32_step->proc~rotate_right32 proc~u64_add u64_add proc~pcg32_step->proc~u64_add proc~u64_mul u64_mul proc~pcg32_step->proc~u64_mul proc~u64_shr u64_shr proc~pcg32_step->proc~u64_shr proc~mix64 mix64 proc~splitmix64_next->proc~mix64 proc~splitmix64_next->proc~u64_add proc~mix64->proc~u64_mul proc~mix64->proc~u64_shr

Module Procedures

private function splitmix64_next_below(gen, n, error) result(r)

Uniform integer in [0, n) from a SplitMix64 generator.

Arguments

Type IntentOptional Attributes Name
type(splitmix64_t), intent(inout) :: gen
integer(kind=default_int), intent(in) :: n
type(error_t), intent(inout), optional :: error

Return Value integer(kind=default_int)

private function pcg32_next_below(gen, n, error) result(r)

Uniform integer in [0, n) from a PCG32 generator. Each attempt consumes two 32-bit outputs, so the stream stays word aligned no matter how many rejections occur.

Arguments

Type IntentOptional Attributes Name
type(pcg32_t), intent(inout) :: gen
integer(kind=default_int), intent(in) :: n
type(error_t), intent(inout), optional :: error

Return Value integer(kind=default_int)