# Drawing variables from truncated normal with mean as another variable

**URL:** <https://discourse.julialang.org/t/drawing-variables-from-truncated-normal-with-mean-as-another-variable/113044>\
**Category:** Probabilistic Programming\
**Tags:** turing\
**Created:** [April 17, 2024, 3:10am UTC](https://discourse.julialang.org/t/drawing-variables-from-truncated-normal-with-mean-as-another-variable/113044 "2024-04-17T03:10:53Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![gonzalo](https://avatars.discourse-cdn.com/v4/letter/g/4bbf92/32.png) [@gonzalo](https://discourse.julialang.org/u/gonzalo)\
**Post date:** [April 17, 2024, 3:10am UTC](https://discourse.julialang.org/t/drawing-variables-from-truncated-normal-with-mean-as-another-variable/113044/1 "2024-04-17T03:10:53Z")

</div>

Hi All,

I want to drawing random variables from truncated normal with mean as another variable. However it didn’t work and I got the following wrong message. Is there anyone who can help me with it?

Gonzalo

```julia
using Turing, Distributions

@model function model(); alpha ~ Uniform(0,1); x = rand(Truncated(Normal(0, alpha),0,1)); end

sample(model(), NUTS(), 1000, thinning=10, discard_initial=1000);

```

Sampling 100%|████████████████████████████████████████████████████████████████████████████████| Time: 0:00:00  
ERROR: MethodError: no method matching randnt(::TaskLocalRNG, ::ForwardDiff.Dual{ForwardDiff.Tag{Turing.TuringTag, Float64}, Float64, 1}, ::ForwardDiff.Dual{ForwardDiff.Tag{Turing.TuringTag, Float64}, Float64, 1}, ::ForwardDiff.Dual{ForwardDiff.Tag{Turing.TuringTag, Float64}, Float64, 1})  
Closest candidates are:  
randnt(::AbstractRNG, ::Float64, ::Float64, ::Float64) at ~/anaconda3/share/julia/packages/Distributions/UaWBm/src/truncated/normal.jl:158

---

<div class="post-metadata">

**Author:** ![ElOceanografo](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/eloceanografo/32/624_2.png) [@ElOceanografo](https://discourse.julialang.org/u/ElOceanografo)\
**Post date:** [April 17, 2024, 3:58am UTC](https://discourse.julialang.org/t/drawing-variables-from-truncated-normal-with-mean-as-another-variable/113044/2 "2024-04-17T03:58:52Z")

</div>

You just need to rewrite it as follows, using the tilde to simulate `x` conditional on `alpha`:

```julia
 @model function model()
       alpha ~ Uniform(0, 1)
       x ~ truncated(Normal(0, alpha), 0, 1)
 end

chain = sample(model(), NUTS(), 1000)

```

---

<div class="post-metadata">

**Author:** ![gonzalo](https://avatars.discourse-cdn.com/v4/letter/g/4bbf92/32.png) [@gonzalo](https://discourse.julialang.org/u/gonzalo)\
**Post date:** [April 17, 2024, 4:40am UTC](https://discourse.julialang.org/t/drawing-variables-from-truncated-normal-with-mean-as-another-variable/113044/3 "2024-04-17T04:40:56Z")

</div>

> [@ElOceanografo](#):
>
> `@model function model()`

Thank you so much. I am so wrong using rand.
