[C++-sig] Overloading sqrt(5.5)*myvector

Bruce Sherwood Bruce_Sherwood at ncsu.edu
Thu Dec 27 05:35:16 CET 2007


Thanks for the suggestion. It hadn't occurred to me to try to override 
numpy as you suggest. However, when I try the code shown below as the 
start of a test of this scheme, I get the following error:

Traceback (most recent call last):
  File "C:\Documents and Settings\Bruce\My 
Documents\0VPythonWork\vectors.py", line 24, in <module>
    numpy.float64.__mul__ = new_mul
TypeError: can't set attributes of built-in/extension type 'numpy.float64'

I'm copying this to the numpy discussion list, as maybe someone there 
will see where to go starting from your suggestion.

Bruce Sherwood

---------------
import numpy

class vector(object):
    def __init__(self,x,y,z):
        self.data = [x,y,z]
    def __mul__(self,other):
        return vector(other*self.data[0],
                     other*self.data[1],
                     other*self.data[2])
    __rmul__ = __mul__

    def show(self):
        print self.data
       
old_mul = numpy.float64.__mul__

def new_mul( self, other ):
    if isinstance( other, vector ):
       return other*self
    else:
       return old_mul( self, other )

numpy.float64.__mul__ = new_mul

a = vector(1,2,3)
a.show()
b = 5*a
b.show()
c = a*7
c.show()


Roman Yakovenko wrote:
> On Dec 26, 2007 8:11 AM, Bruce Sherwood <Bruce_Sherwood at ncsu.edu> wrote:
>   
>> Sorry to repeat myself and be insistent, but could someone please at
>> least comment on whether I'm doing anything obviously wrong, even if you
>> don't immediately have a solution to my serious problem? There was no
>> response to my question (see copy below) which I sent to both the numpy
>> and Boost mailing lists.
>>
>> To the Boost experts: Is there something wrong, or something I
>> could/should change in how I'm trying to define to Boost the overloaded
>> multiplication of a numpy square root (or other numpy function) times my
>> own "vector" object? I'm seeing a huge performance hit in going from
>> Numeric to numpy because Numeric sqrt returned float whereas numpy sqrt
>> returns numpy.float64, so that the result is not one of my vector
>> objects. I don't have a problem with myvector*sqrt(5.5). Here is what I
>> currently am doing:
>>
>> py::class_<vector>("vector", py::init< py::optional<double, double,
>> double> >())
>>      .def( self * double())
>>      .def( double() * self)
>>
>> Desperately,
>>     
>
> If I understand you right, than you can do something like this:
>
> replace __mul__ method of numpy.float64 class:
>
> old_mul = numpy.float64.__mul__
>
> def new_mul( self, other ):
>     if other isinstance( vector ):
>        return other*self
>     else:
>        return old_mul( self, other )
>
> numpy.float64.__mul__ = new_mul
>
> HTH
>
>   



More information about the Cplusplus-sig mailing list