[SciPy-user] Setting the real part of a complex array element

Travis Oliphant oliphant.travis at ieee.org
Mon Jan 16 02:14:33 CST 2006

Paul Ray wrote:

>On Jan 15, 2006, at 6:01 PM, Travis Oliphant wrote:
>>c.real[0] = 1.0
>>The problem is that
>>c[0] is not an array it is a scalar.    This would not have worked  
>>typecode='D' with Numeric either...
>>c.real[0] = 1.0 will work.
>Thanks for the quick answer.  That does indeed fix the problem.
>It is a very strange syntax, however.  Is there some reason why the  
>real part of a scalar can't be set with that syntax (c[0].real = 2.3)?
Yes, because c[0] actually copies an element from the array into a 
scalar (in exactly the same way the Numeric did for only some 
data-types).  NumPy is more consistent and does it for all data-types 
(well void scalars are an exception (to support records) but that's 
another matter).

It used to work before in this particular case because certain versions 
of Numeric would return 0-d arrays for certain data-types (like old 
typecode 'F').   But, this was really an anomaly of Numeric because as I 
pointed out, the syntax would not have worked before if you'd used 
typecode 'D' scalars.

>Is there any big inefficiency with c.real[0]?  
No, not particularly.  What you get with c.real is actually a view of 
the data with strides adjusted so that you skip over the imaginary 
parts.   Then, on this new array you set the particular item to what you 
want.  The difference is that Python allows defining separate behavior 
for "(obj)[index] = <value>"  and "(obj)[index]".  The syntax 
"(obj)[index].attribute = <value>"  is always interpreted as  "a = 
(obj)[index]" followed by "a.attribute = <value>"

>It seems like  
>converting a whole array to real, then grabbing the 0th element,  
>which is counter-intuitive for an operation where I want to grab the  
>0th element and set its real part to some number.
Isn't that a matter of perspective?   I see it has selecting a view of 
the real-part of the array and setting the 0th element of that view to a 
specific value, which seems perfectly natural to me.    The issue is 
that you can't "grab" the 0th element (which by the operation of 
"grabbing" actually copies the data out into another object), and then 
set the corresponding object to anything that will affect the underlying 
array it came from.    That's the concept that needs to be understood.   
In C, something like that would work because you are just dealing with 
memory pointers and C-structures, but in Python that won't work.


More information about the SciPy-user mailing list