[Numpy-discussion] wrong casting of augmented assignment statements
Tue Jan 12 13:16:43 CST 2010
On Tue, Jan 12, 2010 at 7:38 PM, Robert Kern <email@example.com> wrote:
> On Tue, Jan 12, 2010 at 12:31, Sebastian Walter
> <firstname.lastname@example.org> wrote:
>> On Tue, Jan 12, 2010 at 7:09 PM, Robert Kern <email@example.com> wrote:
>>> On Tue, Jan 12, 2010 at 12:05, Sebastian Walter
>>> <firstname.lastname@example.org> wrote:
>>>> 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.
the object does not have a __float__ method.
I've now implemented the __float__ method (to raise an error).
However, it doesn't get called. All objects are casted to 1.
>>> 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
> NumPy-Discussion mailing list
More information about the NumPy-Discussion