Random number function python that include 1 but not include 0

Viewed 79

I need to generate a number from 0 to 1 that include 1 but not include 0

The random.uniform(0,1) function include 0 but not include 1

How is it possible to do that?

3 Answers

It can be as simple as 1 - random.uniform(0,1)

Numpy’s uniform random generator generates values on a [a,b) interval where a is low and b is high.

Samples are uniformly distributed over the half-open interval [low, high) (includes low, but excludes high). In other words, any value within the given interval is equally likely to be drawn by uniform

docs

You could alternatively use:

import random as r
-r.uniform(-1, 0)

So in general:

# random number which excludes a but excludes b
import random as r

def my_uniform(a = 0, b = 1):
    return -r.uniform(-b, -a)
Related