0

I have this function:

def get_starting_centroids(centroids,size,num):
    for i in range(0,num):
        temp = []
        for j in range(0,size):
            random.seed(time.clock())
            g = random.random()
            g = g*.85 + .15
            print "random: %i" %g
            temp.append(g)
        centroids.append(temp)
    return centroids

print tells me it always returns 0. If I test random.random() in the python prompt I get a random value. I don't understand what causes this difference

3
  • 6
    Why are you re-seeding random each round? Commented Dec 4, 2014 at 18:40
  • 1
    Also, even if there is a reason to re-seed every time, random.seed() (without parameters) uses the current system time by default anyway. Commented Dec 4, 2014 at 18:47
  • 2
    Yes, if you call seed inside the loop, you're not getting random numbers at all. Commented Dec 4, 2014 at 18:54

2 Answers 2

7

You are formatting your random value to an integer:

print "random: %i" %g

This floors the value, which is below 1 always, so you always end up with 0.

Print a floating point value:

print "random: %.5f" % g

and you'll see there are actually values there, just between 0.15 and 1.

You should not seed the random generator every round; if you need to seed, just do it once outside the loop:

random.seed()  # seeds to the current system time by default
for j in range(0,size):
    g = random.random()
    g = g*.85 + .15
    print "random: %.5f" % g
    temp.append(g)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks everyone for putting up with these kind of questions. Sometimes you just miss the easy stuff. I think you were the first poster so you got it
1

Your problem is in the formatting.

Use

print "random: %f" %g

You are formatting as decimal, which truncates g, which is a float. g should be added to the temp array correctly, though.

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.