# How to create a random Uniform Distribution between (but excluding) 0 and 10?

**URL:** <https://discourse.julialang.org/t/how-to-create-a-random-uniform-distribution-between-but-excluding-0-and-10/21908>\
**Category:** New to Julia\
**Created:** [March 15, 2019, 10:54am UTC](https://discourse.julialang.org/t/how-to-create-a-random-uniform-distribution-between-but-excluding-0-and-10/21908 "2019-03-15T10:54:42Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![HelgavonLichtenstein](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/helgavonlichtenstein/32/5005_2.png) [@HelgavonLichtenstein](https://discourse.julialang.org/u/HelgavonLichtenstein)\
**Post date:** [March 15, 2019, 10:54am UTC](https://discourse.julialang.org/t/how-to-create-a-random-uniform-distribution-between-but-excluding-0-and-10/21908/1 "2019-03-15T10:54:42Z")

</div>

Hello,

How can I create a random uniform distribution between 0 (which is excluded) and 10 (included).  
That is, the range is between 0 and 10, but 0 itself cannot be included.

```julia
using Distributions
rand(Uniform(0, 10)

```

Using `rand(Uniform(>0, 10)` does not work.

---

<div class="post-metadata">

**Author:** ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)\
**Post date:** [March 15, 2019, 11:04am UTC](https://discourse.julialang.org/t/how-to-create-a-random-uniform-distribution-between-but-excluding-0-and-10/21908/2 "2019-03-15T11:04:01Z")

</div>

Technically, the endpoints have a very small probability (theoretically 0, in practice \approx0 because of floating point). Depending on your application, you can reject and redraw.

Minimal example:

```julia
using Random

"`Uniform(0,b)`, with `0` excluded for sure, and we really mean it."
struct PositiveUniform{T}
    b::T
end

function Base.rand(rng::Random.AbstractRNG, pu::PositiveUniform)
    while true
        r = rand(rng)
        r > 0 && return r * pu.b
    end
end

rand(PositiveUniform(10))

```

> [@HelgavonLichtenstein](#):
>
> Using `rand(Uniform(>0, 10)` does not work.

I am curious why you expected it to work. Adding a closing `)`,

```julia
julia> rand(Uniform(>0, 10))
ERROR: syntax: ">" is not a unary operator

```

informs you that it fails at parsing `>0`. You are dealing with a programming language, and can’t just make up arbitrary expressions and hope it will do something sensible.

---

<div class="post-metadata">

**Author:** ![Elrod](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/elrod/32/22461_2.png) [@Elrod](https://discourse.julialang.org/u/Elrod)\
**Post date:** [March 15, 2019, 11:30am UTC](https://discourse.julialang.org/t/how-to-create-a-random-uniform-distribution-between-but-excluding-0-and-10/21908/3 "2019-03-15T11:30:32Z")

</div>

`rand()` samples a random uniform in [0,1), so 1-rand() is a random uniform in `(0,1]`, and `10*(1-rand())` isa rnadom uniform in `(0,10]`.

This is because the PRNG used (and most PRNGS) generate random unsigned integers, and then mask them to produce a number between `1.0` and `prevfloat(2.0)`.

```julia
julia> bitstring(1.0)
"0011111111110000000000000000000000000000000000000000000000000000"

julia> bitstring(prevfloat(2.0))
"0011111111111111111111111111111111111111111111111111111111111111"

```

The last 52 bits are the fraction component. By generating a random unsigned integer, and setting the first 12 bits to `001111111111`, you get a random `Float64` between 1.0 and `prevfloat(2.0)`.  
Then, most random number generators subtract 1, to get the `[0,1)` range.  
In principle, you could skip a step and use:

```julia
using Random
2.0 - rand(Random.GLOBAL_RNG, Random.SamplerTrivial(Random.CloseOpen12(Float64)))

```

instead. Or:

```julia
@inline mask(x::UInt64) = reinterpret(Float64,(x & 0x000fffffffffffff) | 0x3ff0000000000000)
@inline mask(x::UInt32) = reinterpret(Float32,(x & 0x007fffff) | 0x3f800000)

2.0 - mask(rand(UInt64))

```

You can look at the Julia code for `rand` functions [here](https://github.com/JuliaLang/julia/blob/master/stdlib/Random/src/generation.jl#L25).

---

<div class="post-metadata">

**Author:** ![HelgavonLichtenstein](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/helgavonlichtenstein/32/5005_2.png) [@HelgavonLichtenstein](https://discourse.julialang.org/u/HelgavonLichtenstein)\
**Post date:** [March 15, 2019, 2:24pm UTC](https://discourse.julialang.org/t/how-to-create-a-random-uniform-distribution-between-but-excluding-0-and-10/21908/5 "2019-03-15T14:24:50Z")

</div>

Thank you for your replies. I confess I don’t really understand them - they are at a higher level of coding/Julia than I am currently at, but I understand it is not as straightforward as I had hoped. Nonetheless I will go over and try to understand them.

Could someone please explain what the difference between `[0, 1)` and `(0, 1]` is?

Do you recommend I use the `Random` instead of `Distributions` package, because the `rand()` in `Random` already samples a random uniform number (or did I misunderstand)?

---

<div class="post-metadata">

**Author:** ![tamasgal](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamasgal/32/27946_2.png) [@tamasgal](https://discourse.julialang.org/u/tamasgal)\
**Post date:** [March 15, 2019, 2:27pm UTC](https://discourse.julialang.org/t/how-to-create-a-random-uniform-distribution-between-but-excluding-0-and-10/21908/6 "2019-03-15T14:27:30Z")

</div>

Maybe you tell us what you are up to. You didn’t even tell if you look for integer or floating point numbers, maybe that’s the reason why you are now confused (all the floating point intrinsics)?

---

<div class="post-metadata">

**Author:** ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)\
**Post date:** [March 15, 2019, 2:30pm UTC](https://discourse.julialang.org/t/how-to-create-a-random-uniform-distribution-between-but-excluding-0-and-10/21908/7 "2019-03-15T14:30:08Z")

</div>

> [@HelgavonLichtenstein](#):
>
> Could someone please explain what the difference between `[0, 1)` and `(0, 1]` is?

It’s not code, but standard math notation for open and closed intervals.

> **[Interval (mathematics) | Notations for intervals](https://en.wikipedia.org/wiki/Interval_(mathematics)#Notations_for_intervals)**
>
> The interval of numbers between a and b, including a and b, is often denoted \[a, b\]. The two numbers are called the endpoints of the interval. In countries where numbers are written with a decimal comma, a semicolon may be used as a separator to avoid ambiguity.

---

<div class="post-metadata">

**Author:** ![HelgavonLichtenstein](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/helgavonlichtenstein/32/5005_2.png) [@HelgavonLichtenstein](https://discourse.julialang.org/u/HelgavonLichtenstein)\
**Post date:** [March 15, 2019, 2:35pm UTC](https://discourse.julialang.org/t/how-to-create-a-random-uniform-distribution-between-but-excluding-0-and-10/21908/8 "2019-03-15T14:35:17Z")

</div>

I am writing code from a research paper, but they just state “…animal and plant biomass densities were initialized with random values uniformly distributed between 0 (exclusive) and 10 (inclusive).” I assume the numbers can contain decimals.

---

<div class="post-metadata">

**Author:** ![Balinus](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/balinus/32/243_2.png) [@Balinus](https://discourse.julialang.org/u/Balinus)\
**Post date:** [March 15, 2019, 2:50pm UTC](https://discourse.julialang.org/t/how-to-create-a-random-uniform-distribution-between-but-excluding-0-and-10/21908/9 "2019-03-15T14:50:56Z")

</div>

You might want to give a link to the article.

---

<div class="post-metadata">

**Author:** ![tamasgal](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamasgal/32/27946_2.png) [@tamasgal](https://discourse.julialang.org/u/tamasgal)\
**Post date:** [March 15, 2019, 2:51pm UTC](https://discourse.julialang.org/t/how-to-create-a-random-uniform-distribution-between-but-excluding-0-and-10/21908/10 "2019-03-15T14:51:16Z")

</div>

[https://www.nature.com/articles/ncomms12718.pdf?origin=ppub](https://www.nature.com/articles/ncomms12718.pdf?origin=ppub)

A Google search 😉

---

<div class="post-metadata">

**Author:** ![HelgavonLichtenstein](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/helgavonlichtenstein/32/5005_2.png) [@HelgavonLichtenstein](https://discourse.julialang.org/u/HelgavonLichtenstein)\
**Post date:** [March 15, 2019, 2:54pm UTC](https://discourse.julialang.org/t/how-to-create-a-random-uniform-distribution-between-but-excluding-0-and-10/21908/11 "2019-03-15T14:54:35Z")

</div>

Correct. I am trying to translate the code into Julia. The code they used is in C++, but that does not help me because I don’t know that language at all.

> <https://github.com/fdschneider/schneider_et_al_2016_animaldiversity/blob/release/code/pdef_dynamics_2.4.c>

> <https://github.com/fdschneider/schneider_et_al_2016_animaldiversity/blob/release/code/pdef_dynamics_1.1.h>

---

<div class="post-metadata">

**Author:** ![Balinus](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/balinus/32/243_2.png) [@Balinus](https://discourse.julialang.org/u/Balinus)\
**Post date:** [March 15, 2019, 2:55pm UTC](https://discourse.julialang.org/t/how-to-create-a-random-uniform-distribution-between-but-excluding-0-and-10/21908/12 "2019-03-15T14:55:10Z")

</div>

hahaha! Should have thought about it.

---

<div class="post-metadata">

**Author:** ![Balinus](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/balinus/32/243_2.png) [@Balinus](https://discourse.julialang.org/u/Balinus)\
**Post date:** [March 15, 2019, 3:01pm UTC](https://discourse.julialang.org/t/how-to-create-a-random-uniform-distribution-between-but-excluding-0-and-10/21908/13 "2019-03-15T15:01:03Z")

</div>

It might be easier to understand if you go from the article as the prime inspiration and look at the C code for confirmation? (just an academic suggestion).

You might want to try defining your dynamical system with [DynamicalSystems.jl](https://github.com/JuliaDynamics/DynamicalSystems.jl)

edit - For your initial question @Tamas_Papp provided an elegant solution.

---

<div class="post-metadata">

**Author:** ![nilshg](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/nilshg/32/2283_2.png) [@nilshg](https://discourse.julialang.org/u/nilshg)\
**Post date:** [March 15, 2019, 3:41pm UTC](https://discourse.julialang.org/t/how-to-create-a-random-uniform-distribution-between-but-excluding-0-and-10/21908/14 "2019-03-15T15:41:21Z")

</div>

> [@Elrod](#):
>
> `10*(1-rand())` isa rnadom uniform in `(0,10]` .

This seems to answer your question though? As @Tamas_Papp says `(0, 10]` is just standard mathematical notation for a set excluding 0 and including 10.

So:

```julia
julia> using Plots

julia> a = 10 .* (1 .- rand(100_000))

julia> minimum(a)
1.1877405667881646e-5

julia> histogram(a)

```

![randuni](https://global.discourse-cdn.com/julialang/original/3X/f/a/fa4a111729ae01f06cefb6326db93f95d3fb93ec.png)

Looks good to me!?

---

<div class="post-metadata">

**Author:** ![StevenSiew](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevensiew/32/218393_2.png) [@StevenSiew](https://discourse.julialang.org/u/StevenSiew)\
**Post date:** [March 16, 2019, 10:48am UTC](https://discourse.julialang.org/t/how-to-create-a-random-uniform-distribution-between-but-excluding-0-and-10/21908/15 "2019-03-16T10:48:06Z")

</div>

If you want a random umber generator with (0,1]  
but all you got is a rng with [0,1) then why not create your own

my\_rng = 1 - rng

so my\_rng gives the distribution (0,1]

to get (0,10] you just multiply it by ten

RNG = 10 \* my\_rng

---

<div class="post-metadata">

**Author:** ![foobar\_lv2](https://avatars.discourse-cdn.com/v4/letter/f/ee59a6/32.png) [@foobar\_lv2](https://discourse.julialang.org/u/foobar_lv2)\
**Post date:** [March 16, 2019, 12:05pm UTC](https://discourse.julialang.org/t/how-to-create-a-random-uniform-distribution-between-but-excluding-0-and-10/21908/16 "2019-03-16T12:05:50Z")

</div>

> [@Elrod](#):
>
> `rand()` samples a random uniform in [0,1), so 1-rand() is a random uniform in `(0,1]`

`rand()` samples uniform fixed-point numbers in [0, 1) that are then converted to floating point. It achieves this by sampling a uniform floating point number in `[1,2)` and then subtracting 1.

This means that the output distribution of `rand()` is “ragged”: Instead of the naively expected (sample real number in `[0,1)`, round to the next smaller or equal non-subnormal float), which would make exact `0` vanishingly rare, zero results are very likely.

E.g. `rand(Float32)` has a probability of `eps(Float32) ~ 1e-7` of returning exactly zero, compared to the correct probability of `1e-38` (using normal floats only) or `1e-45` (permitting subnormals, which would be a bad idea). A correct distribution close to `0` is probably prohibitively expensive, but `2e-10 ~ 1/(1<<32)` could be done branch-free by spending 32 bits of entropy instead of 23 bits.

---

<div class="post-metadata">

**Author:** ![fjfranco](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/fjfranco/32/6683_2.png) [@fjfranco](https://discourse.julialang.org/u/fjfranco)\
**Post date:** [March 16, 2019, 2:37pm UTC](https://discourse.julialang.org/t/how-to-create-a-random-uniform-distribution-between-but-excluding-0-and-10/21908/17 "2019-03-16T14:37:11Z")

</div>

Let me make a little contribution. Can’t you just run

rand(0.0+eps(),10.0-eps())

?

Simple and works.

---

<div class="post-metadata">

**Author:** ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)\
**Post date:** [March 16, 2019, 2:50pm UTC](https://discourse.julialang.org/t/how-to-create-a-random-uniform-distribution-between-but-excluding-0-and-10/21908/18 "2019-03-16T14:50:40Z")

</div>

> [@fjfranco](#):
>
> Can’t you just run
> 
> rand(0.0+eps(),10.0-eps())
> 
> ?
> 
> Simple and works.

Nope, it doesn’t work. `rand` has no method for this — it would need something like `Distributions.Uniform`.

Also, even though sometimes one is forced to make regularizations like this as a quick & dirty fix, correct solutions are actually easy in this case.

---

<div class="post-metadata">

**Author:** ![Elrod](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/elrod/32/22461_2.png) [@Elrod](https://discourse.julialang.org/u/Elrod)\
**Post date:** [March 17, 2019, 1:01am UTC](https://discourse.julialang.org/t/how-to-create-a-random-uniform-distribution-between-but-excluding-0-and-10/21908/19 "2019-03-17T01:01:11Z")

</div>

> [@foobar\_lv2](#):
>
> but `2e-10 ~ 1/(1<<32)` could be done branch-free by spending 32 bits of entropy instead of 23 bits.

I imagine this would also be computationally expensive to do with only 32 bits, or?  
Converting a random string of 32 or 64 bits into 23 or 52 random bits of a uniform `[1,2)` distribution only requires two vectorizable and fast CPU instructions.  
Just set the sign and exponential bits correctly via a bitwise `&` and then a bitwise `|`.

How would you actually set the exponential bits for a non-ragged unfirom (0,1)?  
There are an equal number of floating point numbers in the range [0.25, 0.5) as there is [0.5, 1) or [0.125, 0.25).  
So it sounds like you’d need quote some logic in actually processing your remaining bits of entropy to create that correct distribution in the upper bits.

While this uses twice as many bits as `sizeof(T)`, it should still be relatively fast:

```julia
using Random
function nonraggedrand(rng = Random.GLOBAL_RNG)
    zero_sgnexp = 0x000fffffffffffff
    zero_frac = 0xfff0000000000000
    random_exponent = reinterpret(UInt64,rand(rng)) & zero_frac
    random_fraction = rand(rng, UInt64) & zero_sgnexp
    reinterpret(Float64, random_exponent | random_fraction)
end

```

Looks correct from a superficial glance:

```julia
julia> using RNGTest

julia> RNGTest.smallcrushJulia(nonraggedrand)
10-element Array{Any,1}:
 0.5336216850647422                                                                                   
 0.9230989723619558                                                                                   
 0.49280958521636054                                                                                  
 0.6834132908358886                                                                                   
 0.8940787394692569                                                                                   
  (0.5333583536888169, 0.5896538779593443)                                                            
 0.37459169125750136                                                                                  
 0.14003119092065008                                                                                  
 0.7706765198832467                                                                                   
  (0.5617563416418929, 0.9608245561823281, 0.37088087074827114, 0.839032775363961, 0.6894691545291662)

```

The idea is: the ragged randoms have the correct distribution of exponential bits. So, just combine those exponential bits with random fraction bits.

This uses 128 bits for a 64 bit random number, or 64 bits for a 32 bit random number. But I think that’s rather reasonable.  
Many random number generators intentionally discard extra random bits anyway, to help with things like the “birthday problem”, or just for the sake of having a larger state for a longer period.

Maybe it’s a better idea to use a [PCG](https://en.wikipedia.org/wiki/Permuted_congruential_generator#Variants) RXS-M-XS generator, and discard state via combining floating points like this, than it is to use a PCG XSH-RS generator, for example?  
Those generators can be [fast](https://github.com/chriselrod/VectorizedRNG.jl) and are vectorizable. If you’re only sampling serially, vectorization means the cost will be less than 2x for taking this approach.

---

<div class="post-metadata">

**Author:** ![StefanKarpinski](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stefankarpinski/32/24_2.png) [@StefanKarpinski](https://discourse.julialang.org/u/StefanKarpinski)\
**Post date:** [March 17, 2019, 1:51am UTC](https://discourse.julialang.org/t/how-to-create-a-random-uniform-distribution-between-but-excluding-0-and-10/21908/20 "2019-03-17T01:51:55Z")

</div>

Just to try to prevent this thread being overwhelming for a newcomer, let me just highlight the straightforward answer:

```julia
10*(1-rand())

```

Analysis:

- `rand()` is uniform from `[0, 1)`
- `1-rand()` is uniform from `(0, 1]`
- `10*(1-rand())` is uniform from `(0, 10]`

This is a totally fine, simple answer. Is it perfectly uniformly distributed? Meh, maybe, maybe not but the chance that it matters for this use case is negligible.

---

<div class="post-metadata">

**Author:** ![Elrod](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/elrod/32/22461_2.png) [@Elrod](https://discourse.julialang.org/u/Elrod)\
**Post date:** [March 17, 2019, 2:28am UTC](https://discourse.julialang.org/t/how-to-create-a-random-uniform-distribution-between-but-excluding-0-and-10/21908/21 "2019-03-17T02:28:09Z")

</div>

If you want to exclude both 0 and 10, you can use `prevfloat(10.0)*(1-rand())` instead.  
Same argument you gave applies, the answer being uniform from `(0, prevfloat(10.0)]`, i.e. `(0,10)`.

If you don’t, the probability of getting a 10 on any given draw is `1/2^52 = 2.220446049250313e-16`.

[Next page](https://discourse.julialang.org/t/how-to-create-a-random-uniform-distribution-between-but-excluding-0-and-10/21908.md?page=2)
