python-3.x - 如何从 numpy.random.normal() 获取特定范围值?

标签 python-3.x numpy

有没有办法从 numpy.random.normal() 的结果中获取数组的特定范围?不计算所有随机数,它只计算所述范围限制

正常应用

random_numbers = numpy.random.normal(0, 1, 1000)

我想要的是获得这个 random_numbers 的范围,而不需要先计算它

first_100_random_numbers = needs the results of the first 100 values
300th_400th_random_numbers = needs the results of the 300 - 400 values

最佳答案

如果一次生成一个随机数,您只需跟踪它们是否增加了最大值或最小值。您仍然需要计算这些值,但不会遇到内存问题,因为您只需存储三个数字(最大值、最小值和最新随机数)

import numpy as np
max_=0
min_=0
for i in range(1000):
    new_number=np.random.normal(0,1,1)
    if new_number>max_:
        max_=new_number
    if new_number<min_:
        min_=new_number
range_=max_-min_
print(range_)

为了加快计算速度,您可以一次处理更大的 block 。如果你想运行十亿个数字,你可以一次计算一百万个数字并运行循环一千次。修改后的代码和时间结果如下

import numpy as np
import time
max_=0
min_=0
start=time.time()
for i in range(1000):
    new_array=np.random.normal(0,1,1000000)
    new_max=np.max(new_array)
    new_min=np.min(new_array)
    if new_max>max_:
        max_=new_max
    if new_min<min_:
        min_=new_min
range_=max_-min_
print('Range ', range_)
end = time.time()
Time=end - start
print('Time ',Time)


Range 12.421138327443614
Time  36.7797749042511

比较一次运行一个随机数与一次运行十个随机数的结果,看看结果是否有显着差异 (每项运行3次)

一次一个:

new_numbers=[]
for i in range(10):
    new_numbers.append(np.random.normal(0,1,1)[0])
print(new_numbers)
[-1.0145267697638918, -1.1291506481372602, 1.3622608858856742, 0.16024562390261188, 1.062550043104352, -0.4160329548439351, -0.05464203711515494, -0.7416629430695286, 0.35066071936940363, 0.06498345663995017]
[-1.5632632129838873, -1.0314300796946991, 0.5014408178125339, -0.37806631815396563, 0.45396918178048334, -0.6630479858064194, -0.47097483551189306, 0.40734077106402056, 1.1167819302886144, -0.6594075991871857]
[0.4448783416507262, 0.20160041940565818, -0.4781753245124433, -0.7130750653981222, -0.8035305391034386, -0.41543648761183466, 0.25166027175788847, -0.7051417978559822, 0.6017351178904993, -1.3719596304190458]

一次十个:

np.random.normal(0,1,10)
array([-1.79498658,  0.89073416, -0.25302627, -0.17237986, -0.38988131,
       -0.93635678,  0.28824899,  0.52675642,  0.86195635, -0.89584341])
array([ 1.41602405,  1.33800937,  1.87837334,  0.2082182 , -0.25116545,
        1.37953259,  0.34445565, -0.33647043, -0.24414261, -0.14505838])
array([ 0.43848371, -0.60967936,  1.2902231 ,  0.44589728, -2.39725248,
       -1.42715386, -1.0627627 ,  1.15998483,  0.96427742, -2.01062938])

关于python-3.x - 如何从 numpy.random.normal() 获取特定范围值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56784472/

相关文章:

python - 优化 python、numpy 中的矩阵运算

python - 使用 python 3 将系列动态添加到 highcharts

Python错误 'numpy.float64'对象无法解释为整数

python - python 3.9+的nb_conda_kernels等价物是什么?

python - pd.DataFrame 上的 np.where 用于非零索引字典

python - 将线性函数拟合到一组数据后,如何找到函数梯度上的​​误差?

Python Pandas - loc 创建 fortran 有序 numpy 数组

python - scipy.interpolate.interp1d 'kind' 不工作

python - 无法使用 celery 启用 SSL

python - 在 tensorflow 中交叉连接两个矩阵