Romulus
Romulus

Reputation: 1260

random excluding 0 in python

I want to pick up a number between -1.5 and 1.5 but this shouldn't be 0.

I am using:

x = random.uniform( -1.5, 1.5 )

but I have to write a condition to exclude 0 like:

x = 0
while (x==0):
    x = random.uniform( -1.5, 1.5 )

Is it another possibility to write this without a condition?

Upvotes: 1

Views: 11966

Answers (2)

creichen
creichen

Reputation: 1768

You can try

1.5 * (1.0 - random.random())

and then do a random decision for whether to negate the result. Since random.random() < 1.0, you should (numerically) not get a zero.

EDIT:

It has been pointed out (correctly) that this needs two random decisions. To do so with one random decision, use the following:

v = 3.0 * random.random()
result = 1.5 - v
if v >= 1.5:
    result = v - 3.0

If 0.0 <= v < 1.5, you get 1.5 - v, and 0.0 <= range < 1.5.

Otherwise, 1.5 <= v < 3.0, and you get v - 3.0, so 0.0 > range >= -1.5.

Upvotes: 6

andrew cooke
andrew cooke

Reputation: 46872

what you are doing is fine (there's no api method for this), but i suspect that you should have something more like:

epsilon = 1e-10  # for example
while abs(x) < epsilon: x = random.uniform(-1.5, 1.5)

because the most likely reason to avoid zero is for numerical reasons, and typically very small values that are non-zero will also cause problems.

one other thing you could do is take advantage of the half-open nature of random():

x = 1.5 * (1 - random.random())
if random.randint(0, 1): x = -x

but i think the code you have is clearer (and while the above seems technically correct i am not sure i trust it in all cases, with rounding etc).

[edit: i came up with the half-open idea independently of creichen, but got it backwards, so fixed after seeing their code]

Upvotes: 2

Related Questions