How to generate normalized random floats in range (0;1)

I need to generate normal random floats in range [0;1], but randn(Float64) uses a different range.

How to fix it?

The normal distribution has infinite support (in theory). randn samples a normal distribution with variance 1 and mean 0 (so most values are in [-1, 1] and very few values are outside [-5, 5]). If you want to reshape this, you can always add and multiply: almost all outputs of randn()/5 + 0.5 will be in your suggested range.

2 Likes

In the normal distribution, most values are within [-0.6744897501960818, 0.6744897501960818]… :grin:

If you sample from a distribution but throw away any values outside a range, you effectively sample a truncated distribution. I must emphasize that a truncated distribution is not the same as the original distribution, but it’s what you use if you really need a strict range. Distributions.jl supports truncation of univariate distributions, and you use rand to sample. As @gustaphe said, you could truncate to [-a, a] and adjust the values to the range [0, 1], or you could also adjust the mean and variance of the Normal distribution before you truncate it to [0, 1].

Both statements are true :smiley:.

I normally go by the 68-95-99.7 rule, but I never remember the specific numbers so I call it “most”, “almost all”, “pretty much all”.

1 Like