I am beginner in python. I want to generate 3 set of different number within specified range using numpy.random.randint
in python3. (FYI -> Want to implement 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 ; 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?
>>> 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
# 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]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.