简体   繁体   English

在两个数字之间生成随机数

[英]generating random numbers between two numbers

Is it possible to generate random numbers that are almost equally spaced which shouldnot be exactly same as numpy.linspace output是否可以生成几乎等间距的随机数,不应该与numpy.linspace输出完全相同

I look into the numpy.random.uniform function but it doesnot give the required results.我查看了numpy.random.uniform函数,但它没有给出所需的结果。

Moreover the the summation of the values generated by the function should be same as the summation of the values generated by numpy.linspace function.此外,该函数生成的值的总和应该与 numpy.linspace 函数生成的值的总和相同。

code代码

import random
import numpy as np
random.seed(42)
data=np.random.uniform(2,4,10)
print(data)

You might consider drawing random samples around the output of numpy.linspace .您可以考虑在numpy.linspace的输出周围绘制随机样本。 Setting these numbers as the mean of the normal distribution and setting the variance not too high would generate numbers close to the output of numpy.linspace .将这些数字设置为正态分布的平均值并将方差设置得不太高将生成接近numpy.linspace输出的数字。 For example,例如,

>>> import numpy as np
>>> exact_numbers = np.linspace(2.0, 10.0, num=5)
>>> exact_numbers
array([ 2.,  4.,  6.,  8., 10.])
>>> approximate_numbers = np.random.normal(exact_numbers, np.ones(5) * 0.1)
>>> approximate_numbers
array([2.12950013, 3.9804745 , 5.80670316, 8.07868932, 9.85288221])

Maybe this trick by combining numpy.linspace and numpy.random.uniform and random choice two indexes and increase one of them and decrease other help you: (You can change size=10 , threshold=0.1 for how random numbers are bigger or smaller)也许通过结合numpy.linspacenumpy.random.uniformrandom choice two indexes and increase one of them and decrease other帮助您:(您可以更改size=10threshold=0.1随机数如何更大或更小)

import numpy as np
size = 10
theroshold = 0.1
r = np.linspace(2,4,size) # r.sum()=30
# array([2.        , 2.22222222, 2.44444444, 2.66666667, 2.88888889,
#        3.11111111, 3.33333333, 3.55555556, 3.77777778, 4.        ])

c = np.random.uniform(0,theroshold,size)
# array([0.02246768, 0.08661081, 0.0932445 , 0.00360563, 0.06539992,
#        0.0107167 , 0.06490493, 0.0558159 , 0.00268924, 0.00070247])

s = np.random.choice(range(size), size+1)
# array([5, 5, 8, 3, 6, 4, 1, 8, 7, 1, 7])

for idx, (i,j) in enumerate(zip(s, s[1:])):
    r[i] += c[idx]
    r[j] -= c[idx]

print(r)
print(r.sum())

Output:输出:

[2.         2.27442369 2.44444444 2.5770278  2.83420567 3.19772192
 3.39512762 3.50172642 3.77532244 4.        ]

30

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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