[Numpy-discussion] Nasty bug using pre-initialized arrays

Robert Kern robert.kern@gmail....
Fri Jan 4 16:10:49 CST 2008


Stuart Brorson wrote:
> On Fri, 4 Jan 2008, Stuart Brorson wrote:
> 
>>> I just discovered this today.  It looks like a bug to me.  Please
>>> flame me mercilessly if I am wrong!  :-)
> 
> FWIW, here's what Matlab does:
> 
>>> A = rand(1, 4) + rand(1, 4)*i
> 
> A =
> 
>    Columns 1 through 3
> 
>     0.7833 + 0.7942i   0.6808 + 0.0592i   0.4611 + 0.6029i
> 
>    Column 4
> 
>     0.5678 + 0.0503i
> 
>>> B = zeros(1, 4)
> 
> B =
> 
>       0     0     0     0
> 
>>> for idx=1:4; B(idx) = A(idx); end
>>> B
> 
> B =
> 
>    Columns 1 through 3
> 
>     0.7833 + 0.7942i   0.6808 + 0.0592i   0.4611 + 0.6029i
> 
>    Column 4
> 
>     0.5678 + 0.0503i
> 
> 
> I realize NumPy != Matlab, but I'd wager that most users would think
> that this is the natural behavior......

Well, that behavior won't happen. We won't mutate the dtype of the array because
of assignment. Matlab has copy(-on-write) semantics for things like slices while
we have view semantics. We can't safely do the reallocation of memory [1].

[1] Well, we do have a .resize() method which will do the reallocation and raise
an exception if there are views lingering about. However, this is only done when
explicitly asked for because this is a feature that is useful in a limited
number of situations. We will not allow it to be done implicitly.

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