generating random tuples in python
Steven D'Aprano
steven at REMOVE.THIS.cybersource.com.au
Tue Apr 21 05:08:11 CEST 2009
On Mon, 20 Apr 2009 11:39:35 -0700, per wrote:
> hi all,
>
> i am generating a list of random tuples of numbers between 0 and 1 using
> the rand() function, as follows:
>
> for i in range(0, n):
> rand_tuple = (rand(), rand(), rand()) mylist.append(rand_tuple)
>
> when i generate this list, some of the random tuples might be very close
> to each other, numerically. for example, i might get:
[...]
> how can i maximize the amount of "numeric distance" between the elements
> of
> this list, but still make sure that all the tuples have numbers strictly
> between 0 and 1 (inclusive)?
Well, the only way to *maximise* the distance between the elements is to
set them to (0.0, 0.5, 1.0).
> in other words i want the list of random numbers to be arbitrarily
> different (which is why i am using rand()) but as different from other
> tuples in the list as possible.
That means that the numbers you are generating will no longer be
uniformly distributed, they will be biased. That's okay, but you need to
describe *how* you want them biased. What precisely do you mean by
"maximizing the distance"?
For example, here's one strategy: you need three random numbers, so
divide the complete range 0-1 into three: generate three random numbers
between 0 and 1/3.0, called x, y, z, and return [x, 1/3.0 + y, 2/3.0 + z].
You might even decide to shuffle the list before returning them.
But note that you might still happen to get (say) [0.332, 0.334, 0.668]
or similar. That's the thing with randomness.
--
Steven
More information about the Python-list
mailing list