The Normal distribution with upper and lower bound

I want to have a normal distribution with upper and lower bound. the code:

        model = pm.Model()
        with model:
            x1=pm.math.maximum(pm.math.minimum(pm.Normal('s',mu=0.45,sd=0.15), 0.7),0.4)
            x1.name="x1"
            step=pm.HamiltonianMC(vars=[x1])

        def run(n_samples=100):
               `with model:`
                        trace = pm.sample(n_samples,trace=[x1],step=step)
                 pm.traceplot(trace,varnames=['x1'])
        if __name__=='__main__':
                run()

however, there is invalid when using HMC sampler. why? is the code wrong?

The standard way to do in PyMC3 is to create a bound distribution:

In [1]: import pymc3 as pm

In [2]: BoundNormal=pm.Bound(pm.Normal, 0, 1)

In [3]: with pm.Model():
   ...:     bound_mu = BoundNormal('mu', mu=0., sd=1.)
   ...:     trace = pm.sample()

Notice that, you cannot assign observation to a bound variable. If you want to do bounded observed you should use a censored model.

1 Like

Thanks very much !:grin: