Marco - 4 months ago 9

Python Question

I'm stuck with a problem. I have to implement an algorithm in python which needs a random number X such as Pr[X ≥ k] = 1/k. I don't know if already exists a distribution which can give me this exact value or if there is a way to implement this random generator using the simple random python library. Is there a way to do this? Thank you in advance for your help!

Answer

The easiest attempt is to make

```
X = 1.0 / random.random()
```

However, `random.random()`

can have a value of zero, so this may result in a divide-by-zero error. The value can never be 1.0, according to the documentation, so use

```
X = 1.0 / (1.0 - random.random())
```

For this distribution,

Pr[X ≥ k] = Pr[1.0 - random.random() ≤ 1/k] = 1/k

Of course, all this assumes that k ≥ 1. Your condition makes no sense otherwise. I also assumed that X was to be a continuous random variable, from 1 to plus infinity. If X is to be an positive integer (thus k is also a positive integer), just take the floor of the formula I gave.

Source (Stackoverflow)

Comments