[Numpy-discussion] numpy.random.shuffle
Robert Kern
robert.kern at gmail.com
Wed Nov 22 11:17:19 CST 2006
Christopher Barker wrote:
> Robert Kern wrote:
>> This is really a thinko on my part.
>
> What, exactly, is a thinko?
Like a typo except that the fault lies with the brain, not the fingers.
>> I copied the algorithm from Python's random
>> module. At the core of it is a set of swaps:
>>
>> x[i], x[j] = x[j], x[i]
>>
>> With the kind of sequences that the stdlib random module is expecting, that
>> makes perfect sense. However, with N-dim arrays (N > 1), x[i] is a *view* into
>> the array. By the time that x[j] = x[i] gets executed, x[i] = x[j] has already
>> executed and the underlying memory that x[i] points to has been modified.
>
> wouldn't something like:
>
> temp = x[i].copy()
> x[i], x[j] = x[j], temp
>
> work?
>
> In any case, it should raise an error if ndim > 1, rather than giving a
> wrong result.
The method is intended to work on sequences in general, not just numpy arrays,
so I can't really use .copy() or even test for ndim > 1.
One possibility is to check if the object is an ndarray (or subclass) and use
.copy() if so; otherwise, use the current implementation and hope that you
didn't pass it a Numeric or numarray array (or some other view-based object).
--
Robert Kern
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
More information about the Numpy-discussion
mailing list