Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gb_gen_range_isze generates random values outside of its range #50

Open
OetkenPurveyorOfCode opened this issue Feb 3, 2024 · 0 comments

Comments

@OetkenPurveyorOfCode
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant