繁体   English   中英

分布在-2和2之间且分布均匀的10个随机点的列表

[英]List of 10 random points between -2 and 2 with uniform distribution

如何列出一个介于2和2之间且分布均匀的10个随机点? Python不断告诉我范围为负数或太小

这是我到目前为止的内容:

import random
randint = random.uniform((1, 10),10)
print (randint)

random.uniform仅接受2个参数:下限和上限。 因此,您需要调用10次:

[random.uniform(-2, 2) for _ in range(10)]

您也可以使用Numpy的版本。 您可以在此处指定元素数:

np.random.uniform(-2, 2, 10)

random.uniform接受两个参数,最小值和最大值,

因此,您可以使用列表推导来获取10个随机数:

[random.uniform(-2, 2) for _ in range(10)]

这是一个示例输出:

[-1.372898354215351, 0.7685608600440506, -0.6975671872462357, -0.3631270499386905, -0.36208667438256414, 0.2822971553695144, 1.427192211459123, -0.9077597437164586, -0.8081649192178384, -1.6619848742793604]

如果我理解正确,这就是您想要的。

l = []

for _ in range(10):
    l.append(random.uniform(-2, 2))

print(l)

[1.6348754396814087,
 1.8481047445800565,
 -0.125676526622843,
 -0.7042785180355264,
 1.2117300078323434,
 1.2910590071566834,
 -1.939559252995089,
 1.458643196526031,
 1.83268811338445,
 0.03584910568687105]

我认为您正在尝试这样做:

import random
my_random_numbers = [] # initialize list
for i in range(10): # you need 10 numbers
    my_random_num = random.uniform(-2, 2) # they should be between -2, 2
    print(my_random_num) # make sure numbers meet satisfaction
    my_random_numbers.append(my_random_num) # add to our list

输出:

1.6876915611870968
-0.8178893369346687
0.3262903557811643
0.6888991431631117
-1.9753672418552077
0.463925233718546
-0.44685838294827285
-1.1500656906098317
-0.8825768728082863
-1.0350040728799694

做这个:

np.random.uniform(-2, 2, 10)

暂无
暂无

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

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