[Numpy-discussion] wrong casting of augmented assignment statements

Robert Kern robert.kern@gmail....
Tue Jan 12 12:38:51 CST 2010


On Tue, Jan 12, 2010 at 12:31, Sebastian Walter
<sebastian.walter@gmail.com> wrote:
> On Tue, Jan 12, 2010 at 7:09 PM, Robert Kern <robert.kern@gmail.com> wrote:
>> On Tue, Jan 12, 2010 at 12:05, Sebastian Walter
>> <sebastian.walter@gmail.com> wrote:
>>> Hello,
>>> I have a question about the augmented assignment statements *=, +=, etc.
>>> Apparently, the casting of types is not working correctly. Is this
>>> known resp. intended behavior of numpy?
>>
>> Augmented assignment modifies numpy arrays in-place, so the usual
>> casting rules for assignment into an array apply. Namely, the array
>> being assigned into keeps its dtype.
>
> what are the usual casting rules?

For assignment into an array, the array keeps its dtype and the data
being assigned into it will be cast to that dtype.

> How does numpy know how to cast an object to a float?

For a general object, numpy will call its __float__ method.

>> If you do not want in-place modification, do not use augmented assignment.
>
> Normally, I'd be perfectly fine with that.
> However, this particular problem occurs when you try to automatically
> differentiate an algorithm by using an Algorithmic Differentiation
> (AD) tool.
> E.g. given a function
>
> x = numpy.ones(2)
> def f(x):
>   a = numpy.ones(2)
>   a *= x
>   return numpy.sum(a)
>
> one would use an AD tool as follows:
> x = numpy.array([adouble(1.), adouble(1.)])
> y = f(x)
>
> but since the casting from object to float is not possible the
> computed gradient \nabla_x f(x) will be wrong.

Sorry, but that's just a limitation of the AD approach. There are all
kinds of numpy constructions that AD can't handle.

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