How to sample from a truncated distribution given a certain known variance?

I did notice that when I sample from a truncated distribution the sample variance I get is not the one that I would expect from the distribution, but one “corrected” by the truncation process:

using Distributions, Statistics

μ = 0
σ = 1
l = -0.5
u = 0.5

d = Truncated(Normal(μ,σ),l,u)
sampledData = rand(d,100000)
minimum(sampledData)  # ok
maximum(sampledData) # ok
mean(sampledData)   # ok
var(sampledData)^(1/2) # 0.28 instead of 1. Same if I use TruncatedNormal

Is there a way to “correct” the initial sigma so that the sampled data have a given known variance ?

(Edited) You cannot get a variance of one. E(x^2) for x between -.5 and .5 will never be equal to one.

You can compute the variance of the truncated normal directly by computing its pdf (which is just a constant multiple of the normal pdf). Here is some R code to compute this (sorry, I had RStudio open):

var_truncated <- function(sigma) {
     # scale the normal pdf by the area between -.5 and .5
     scaling <- integrate(function(x) dnorm(x, sd = sigma), -.5, .5)$value
     integrate(function(x) x^2 * dnorm(x, sd = sigma) / scaling, -.5, .5)$value
# find the sigma s.t. the variance of truncated distribution is 1
# uniroot(function(x) var_truncated(x) - 1, c(1,1e6))

# EDIT: appears the limit of the variance is ~.08333

EDIT: typo in my code led to an incorrect conclusion

Of course it will be lower, you’ve truncated the distribution! In the Normal case it is known analytically,

Perhaps your question is about how to set sigma such that the truncated variance is 1. In that case you can use the formula for the variance on the wiki page to do that, given some predefined truncation levels, but it may not be possible as pointed out above.