Created
November 19, 2025 00:36
-
-
Save yeiichi/84529169c5adaa1b492888aca70e1325 to your computer and use it in GitHub Desktop.
Generate Gaussian-distributed random floats strictly within [a, b] using rejection sampling (no clipping)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import numpy as np | |
| def gaussian_random_reject(a, b, mean=None, std=None, size=1): | |
| """ | |
| Generate Gaussian-distributed random floats strictly within [a, b] | |
| using rejection sampling (no clipping). | |
| Parameters: | |
| a, b : float | |
| Range limits. | |
| mean : float (optional) | |
| Mean of the Gaussian. Defaults to midpoint of [a, b]. | |
| std : float (optional) | |
| Standard deviation. Defaults to (b - a) / 6. | |
| size : int | |
| Number of samples to return. | |
| Returns: | |
| numpy.ndarray of shape (size,) | |
| """ | |
| if mean is None: | |
| mean = (a + b) / 2 | |
| if std is None: | |
| std = (b - a) / 6 | |
| samples = [] | |
| while len(samples) < size: | |
| # generate in batches for efficiency | |
| batch = np.random.normal(loc=mean, scale=std, size=size) | |
| # keep only those within [a, b] | |
| accepted = batch[(batch >= a) & (batch <= b)] | |
| samples.extend(accepted.tolist()) | |
| return np.array(samples[:size]) | |
| # Example usage: | |
| """ | |
| vals = gaussian_random_reject(1, 10, size=5) | |
| print(vals) | |
| """ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment