B Furtado
B Furtado

Reputation: 1500

Truncating a random gammavariate result to an upper limit

I want to draw a number from a gammavariate, but I want to set an upper limit. Why this does not work?

import random
[int(random.gammavariate(3, 3)) if x < 21 else 20 for x in range(1)]

Out[59]: [22]

Thanks.

Upvotes: 0

Views: 111

Answers (2)

BPL
BPL

Reputation: 9863

If I've understood correctly you want to clamp a random value following the gamma distribution in a certain range [0-20], you could do it like this:

import random


def clamp(x, min_value, max_value):
    return max(min(max_value, x), min_value)

min_value, max_value = 0, 20
print([clamp(int(random.gammavariate(3, 3)), min_value, max_value)
       for v in range(1)])

In your example, you were using the index x instead of your random gamma value, I'm assuming that's not what you want

Upvotes: 0

Saeid
Saeid

Reputation: 4265

Why making things complicated?

x is always 0 in your list comprehension.

try it this way:

x = int(random.gammavariate(3,3))
[x if x < 21 else 20]

Upvotes: 1

Related Questions