Random Numbers in a range around a median

徘徊边缘 提交于 2020-01-03 02:36:17

问题


I have a median and a standard deviation, what i want is to generate random numbers between the median-std and the median+std.

I know how to do it like this:

import numpy as np
import random as rnd

median=30
std=15
random_nr=rnd.randint(median-std,median+std)

I also found the numpy.random.normal function but it doesn't seem to do what i need. Is there any other way of doing it? It would be great if the random generator would generate numbers in mirror as to the median, for example, an output for 6 generated random numbers should look like this:

numbers=magicfunction(median,std,6)
[29,31,20,40,25,35]

回答1:


Here it is, if the size is odd then it will only generate couples (as your request) and then a single number at the end of the array.

import numpy as np
import random as rnd

median=30
std=15
def generatearray(median,std,size):
    output=[0]*size    
    for index in range(0,size/2):
        random_nr=rnd.randint(-std,std)
        output[2*index]=median+random_nr
        output[2*index+1]=median-random_nr
    if(size % 2 != 0):
        output[size-1]=rnd.randint(median-std,median+std)
    return output

print generatearray(median,std,6)


来源:https://stackoverflow.com/questions/46565585/random-numbers-in-a-range-around-a-median

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!