Skip to content

gb_gen_range_isze generates random values outside of its range #50

Description

@OetkenPurveyorOfCode
isize gb_random_range_isize(gbRandom *r, isize lower_inc, isize higher_inc) {
	u64 u = gb_random_gen_u64(r);
	isize i = *cast(isize *)&u; // may be negative if u64 has a bit pattern corresponding to a negative isize
	isize diff = higher_inc-lower_inc+1;
	i %= diff; // modulus of negative i can happen here
	i += lower_inc;
	return i; 
}

A possible fix could be:

isize gb_random_range_isize(gbRandom *r, isize lower_inc, isize higher_inc) {
	u64 u = gb_random_gen_u64(r);
	usize diff = higher_inc-lower_inc+1;
	u %= diff;
	u += lower_inc;
	return cast(isize)u;
}

But you may want to look into better debiasing or faster biased random number within range generation: https://www.pcg-random.org/posts/bounded-rands.html

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions