[Numpy-discussion] Re: reshape and ravel methods of arrays now return views or raise error

Tim Hochberg tim.hochberg at cox.net
Tue Mar 28 22:27:05 CST 2006


Robert Kern wrote:

>Charles R Harris wrote:
>  
>
>>On 3/28/06, *Zachary Pincus* <zpincus at stanford.edu
>><mailto:zpincus at stanford.edu>> wrote:
>>
>>    Let me give a more concrete example, pulled from some code I was
>>    actually using.
>>
>>    The code is obviously a bit flawed, but it worked fine with numpy up
>>    until today. Now it breaks when a and b aren't both c-strided:
>>    def distance_squared(a, b):
>>         return numpy.sum( (a.ravel() - b.ravel())**2 )
>>
>>def distance_squared(a,b)
>>    return ((a - b)**2).sum()
>>
>>The function should probably throw an error if a and b don't have the
>>same shape and order and now it does.
>>    
>>
>
>Does it?
>
>In [55]: def distance_squared(a, b):
>   ....:     return ((a - b) ** 2).sum()
>   ....:
>
>In [56]: distance_squared(arange(5), arange(3)[:,newaxis])
>Out[56]: 55
>  
>
Right. It will work with any two arrays that can be broadcast to the 
same shape. Given numpy's rules, that's arguably the right thing to do 
in general although whether it's the right thing to do here depends on 
the specific application, which I don't know.

Still, this is almost certainly better than the original case, which 
will blithely compute the distance_squared for any two arrays with the 
same total size. Then again, it's possible that's what the author really 
wanted. Unlikely, I think, but possible.

Regards,

-tim









More information about the Numpy-discussion mailing list