2

I am beginner in python. I want to generate 3 set of different number within specified range using numpy.random.randint in python3. (F.Y.I -> 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?

1
  • Your only integer in the range 38 (inclusive) and 39 (non inclusive) is 38, that's why you always get 38, same for the second ranges - your ranges do not allow anything else as they are not inclusive. Commented Feb 10, 2018 at 19:54

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.