Search code examples
pythonnumpyrandom-data

Generate random bytearray from a distribution


I am looking for a way to generate random bytes sampled from specified underlying distribution. e.g. bytes generated from a normal distribution with given mean and variance, bytes generated from poisson distribution with specified lambda and so on.

I've used numpy.random.bytes(...) as far the documentation mentions, it generates random bytes which I presume are sampled from uniform distribution. However, I want a numpy based snippet to generate specified number of bytes from possibly any of the specified distributions listed numpy sampling distributions


Solution

  • Generate random values within the range [0, 256) or normalize them to that range (by multiplication, subtraction or addition) and then truncate the results to uint8 integers.That result can then be converted to bytes.

    E.g., generating a normal (Gaussian) distribution around the midpoint:

    values = np.random.normal(128, 35, size=32)
    as_bytes = values.astype(np.uint8).tobytes()
    

    Take into account that not all random distributions are suitable for expression in a series of 0-255 integers.