Home > Back-end >  Generate random sampling of numbers within a range
Generate random sampling of numbers within a range

Time:10-03

Trying to understand how to do this in python, to generate n samples for the random variable.

ƒY (y) { ¼ 0 ≤ y ≤ 4, 0 otherwise}

Below is what I was thinking:

import random as rnd
import scipy.stats as scpy
import matplotlib.pyplot as plt

#scpy.binom.rvs(n, p, size)
for i in range(5):
    rnd_binom = scpy.binom.rvs(n = 12, p = 0.6)
    print(rnd_binom)

But I think I need to somehow add a condition such that if the value is greater or equal to 0 and less than or equal to 4, it should be multiplied by 1/4. How can I layer that in?

CodePudding user response:

You can bring the condition like this,

... your code ...
for i in range(5):
    n = rnd.randrange(0, 10)
    rnd_binom = scpy.binom.rvs(n = 12, p = 0.6)
    if n >= 0 and n <= 4:
        rnd_binom = rnd_binom * 0.25
    print(rnd_binom)

CodePudding user response:

You can use the python random module in order to generate random number within a specific range:

import random
random.randint(0, 4) # random integer
random.uniform(0, 4) # random float
  • Related