def sample_truncated_gaussian(mu=<NUM_LIT:0>, sigma=<NUM_LIT:1>, lb=-np.Inf, ub=np.Inf):
<EOL>mu, sigma, lb, ub = np.broadcast_arrays(mu, sigma, lb, ub)<EOL>shp = mu.shape<EOL>if np.allclose(sigma, <NUM_LIT:0.0>):<EOL><INDENT>return mu<EOL><DEDENT>cdflb = normal_cdf(lb, mu, sigma)<EOL>cdfub = normal_cdf(ub, mu, sigma)<EOL>cdfsamples = cdflb + np.random.rand(*shp) * (cdfub-cdflb)<EOL>cdfsamples = np.clip(cdfsamples, <NUM_LIT>, <NUM_LIT:1>-<NUM_LIT>)<EOL>zs = -np.sqrt(<NUM_LIT:2>) * special.erfcinv(<NUM_LIT:2> * cdfsamples)<EOL>xs = sigma * zs + mu<EOL>xs = np.clip(xs, lb, ub)<EOL>return xs<EOL>
Sample a truncated normal with the specified params. This
is not the most stable way but it works as long as the
truncation region is not too far from the mean.