Udayan Mitra
Udayan Mitra

Reputation: 23

How can i generate random variables using np.random.zipf for a given range of values?

I have a given price range and i had used random uniform to get random generated random results from it. How can i introduce np.random.zipf to do the same ?

i have tried the following :

a = np.random.zipf((randint(1, 6000000)), size=None)
print(a)

But it seems to be providing no return values, and it keeps running the code without any termination

order_total_price_range1 = round(random.uniform(850, 560000), 5)
order_total_price_range2 = round(random.uniform(850, 560000), 5)

I expected to get max and min values from the zipf distribution, but currently not getting any results returned.

Upvotes: 2

Views: 802

Answers (2)

Severin Pappadeux
Severin Pappadeux

Reputation: 20110

While @RobinNicole is right wrt Zipf distribution, you could simulate truncated Zipf using discrete sampling. Along the lines

import numpy as np
from matplotlib import pyplot as plt

def Zipf(a: np.float64, min: np.uint64, max: np.uint64, size=None):
    """
    Generate Zipf-like random variables,
    but in inclusive [min...max] interval
    """
    if min == 0:
        raise ZeroDivisionError("")

    v = np.arange(min, max+1) # values to sample
    p = 1.0 / np.power(v, a)  # probabilities
    p /= np.sum(p)            # normalized

    return np.random.choice(v, size=size, replace=True, p=p)

min = np.uint64(3)
max = np.uint64(8)

q = Zipf(1.2, min, max, 10000)
print(q)

h, bins = np.histogram(q, bins = int(max-min+1),range=(min-0.5,max+0.5))
print(h)
print(bins)

plt.hist(q, bins = bins)
plt.title("Zipf")
plt.show()

Will make graph like this

enter image description here

Upvotes: 3

Robin Nicole
Robin Nicole

Reputation: 662

You cannot tune the parameter of the Zipf law to restrict it to a given interval as you do it with the uniform distribution. The reason for that is that the Zipf distribution is always defined on the set of all the positive integers independently of its parameters.

Upvotes: 0

Related Questions