Please help me understand this small code

Started by
3 comments, last by musafir2007 12 years, 8 months ago
Hi, I am trying to port a peice of code from C into python:

In C, this is the code:
[source]
int j = 0;
int i = 0;
float points[1024];

srand(117);

for (i = 0; i < 512; ++i)
{
points[j++] = (rand() / (float)RAND_MAX) * 768.0f - 256.0f;
points[j++] = (rand() / (float)RAND_MAX) * 768.0f - 256.0f;
}
[/source]

I don't really understand what is going on here. I know srand(117) initializes the random generator with seed 117, but I can't make sense of out the math.

In python, I would do something like this?

[source]
import random

points = []

random.seed(117)

for i in range(512):
points.append((random.random() / ???) * 768.0 - 256.0)
points.append((random.random() / ???) * 768.0 - 256.0)

[/source]

btw, this piece of code is taken from here: http://www.amanithvg.com/testsuite/amanithvg_sre/tests/rendering_rasterizer.inc

Please help
Advertisement
RAND_MAX is the maximum value rand() can return, so (rand() / (float)RAND_MAX) gives you a random value in range [0.0-1.0]. So the whole thing gives you a number in range [-256, 512]. Why they do this I don't know. Also note that seeding the random generator with a fixed seed give you the same sequence of random numbers each time.
Thanks,
but how can I know the RAND_MAX for random generator in python? also is RAND_MAX affected by the seed?
Look at the documentation for the range of values returned by the random function. For rand in C, its from 0 to RAND_MAX, for example, which is why you divide by RAND_MAX to get a random number from 0 to 1.
oh ok, got it! so I don't actually need to divide by RAND_MAX in python.
I can just do random.random() which will return the number between 0 and 1.

Thanks!

This topic is closed to new replies.

Advertisement