简体   繁体   English

仅使用 numpy 中的 random.random 获取 -2 和 2 之间的浮动随机数?

[英]Get floating random numbers between -2 and 2 only using random.random in numpy?

I would like to get a random floating-point value between -2 and +2.我想得到一个介于 -2 和 +2 之间的随机浮点值。 The best I could do is:我能做的最好的是:

my_array = [-1, 1]
change_sign = []
for i in range(6):
  change_sign.append(my_array[np.random.randint(low=0, high=2)] * 2)
print(change_sign)
results = np.random.random([6]) * change_sign

Desired output:所需的 output:

[-1.14, -0.25, 0.33, 1.75, 1.99, -0.83]

But I feel like it could be done even more easily.但我觉得它可以更容易地完成。 I don't want to use other numpy methods (like uniform), just random and randint.我不想使用其他 numpy 方法(如统一),只是随机和随机。

How could I do that?我怎么能那样做?

np.random.random returns a random float between 0.0 and 1.0 np.random.random返回 0.0 到 1.0 之间的随机浮点数

so you can multiply by 4 and subtract 2 so the range would be -2.0 to 2.0所以你可以乘以 4 并减去 2,所以范围是 -2.0 到 2.0

np.random.random(6)*4 - 2
array([ 1.41044053, -0.97521584,  1.55446329, -0.54314241, -1.55691897,
        0.28276924])

To get 'n' (= 10) random numbers between 'a' (= -2) and 'b' (= 2) use this formula:要获得 'a' (= -2) 和 'b' (= 2) 之间的 'n' (= 10) 个随机数,请使用以下公式:

n = 10
a = -2
b = 2

r = a + (b - a) * numpy.random.random(n)

Result:结果:

array([ 0.29379447,  1.0017837 ,  0.46310858, -1.79242304,  1.04047713,
       -0.71521254,  0.32970214,  1.16248318, -1.12456574, -0.47470759])

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

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