问题
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.
回答1:
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
回答2:
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.
来源:https://stackoverflow.com/questions/57413721/how-can-i-generate-random-variables-using-np-random-zipf-for-a-given-range-of-va