简体   繁体   English

在Python中生成3个不同的随机数

[英]Generate 3 different random number in Python

I am beginner in python. 我是python的新手。 I want to generate 3 set of different number within specified range using numpy.random.randint in python3. 我想在python3中使用numpy.random.randint在指定范围内生成3套不同的数字。 (FYI -> Want to implement K-Means) (仅供参考->要实施K-Means)

I am using this code 我正在使用此代码

# Number of clusters
k = 3
# X coordinates of random centroids
C_x = np.random.randint(38.8, 39.4, size=k)
# Y coordinates of random centroids
C_y = np.random.randint(-77.5,-76.5, size=k)
C = np.array(list(zip(C_x, C_y)), dtype=np.float32)
print(C)

But each iteration gives me same set of values 但是每次迭代都给我相同的一组值

[[ 38. -77.]
 [ 38. -77.]
 [ 38. -77.]]

Where am I going wrong? 我要去哪里错了?

The randint() function operates on integers ; randint()函数整数进行运算; your floats are floored to integers before taking the random value. 您的浮点数必须取整为整数,然后再取随机值。 Because the second values is exclusive , you are producing a range of just one value each. 由于第二个值是互斥的 ,因此您生成的每个值的范围仅为一个

Either pass in integers for the low and high values (and pick a larger range), or use one of the distribution functions . 为低和高值传递整数 (并选择较大的范围),或者使用分布函数之一 The numpy.random.uniform() function is fine for your needs, I presume? numpy.random.uniform()函数适合您的需求吗?

>>> C_x = np.random.uniform(38.8, 39.4, size=k)
>>> C_y = np.random.uniform(-77.5,-76.5, size=k)
>>> np.array(list(zip(C_x, C_y)), dtype=np.float32)
array([[ 39.04865646, -76.83393097],
       [ 39.06672668, -76.70361328],
       [ 39.35120773, -77.00741577]], dtype=float32)

I used numpy.random.uniform 我用了numpy.random.uniform

# Number of clusters
k = 3
# X coordinates of random centroids
C_x = np.random.uniform(38.8, 39.4, size=k)
# Y coordinates of random centroids
C_y = np.random.uniform(-77.5,-76.5, size=k)
C = np.array(list(zip(C_x, C_y)), dtype=np.float32)
print(C)

and it worked. 而且有效。

[[ 38.88471603 -77.37638855]
 [ 38.99485779 -76.99333954]
 [ 38.97389603 -77.27649689]]

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

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