简体   繁体   中英

How can I generate random (int) values with specific size and mean?

I need to generate 1000 samples (int) with average 2. Do you think such a function already exists in python?

If you want to stick to the standard library, you can use the random libary

import random
import statistics

example = [random.randint(0, 4) for _ in range(1000)]
print(statistics.mean(example))

I arbitrarily selected 0 and 4 for the range passed to randint. You can select other ranges so long as they are centered on 2.

NumPy's random.randint(low, high=None, size=None, dtype=int) generates "random integers from the “discrete uniform” distribution of the specified dtype in the “half-open” interval [ low , high )".

Therefore, to generate random integers with mean of 2 just make sure that the interval you specify is centred on 2.

>>> import numpy as np
>>> np.random.randint(0,5,10000000).mean()
1.999827
>>> np.random.randint(-10,15,10000000).mean()
2.000426

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM