Hey,
What is the best solution to get this code working? Anyone a good idea?
------------------ test.py ----------------------------------------------- import numpy import numpy.linalg
class afloat: def __init__(self,x): self.x = x
def __add__(self,rhs): return self.x + rhs.x
def sin(self): return numpy.sin(self.x)
def inv(self): return numpy.linalg.inv(self.x)
def trace(self): return 0
y = afloat(numpy.eye(3)) z = afloat(numpy.ones(3)) print y + z # works print numpy.sin(y) # works print numpy.trace(y) # doesn't work...??? print numpy.linalg.inv(y) # doesn't work ...???
-------------------- end test.py --------------------------------
=== Explanation why I need that ===
I have the following problem. I need to do numerical calculations on generalized versions of real numbers. In particular with truncated Taylor polynomials. I've implemented that as a class that I called TC. To define what the multiplication of two Taylor polynomials is I use operator overloading. Additionally, I need to compute sine, cosine, exp, etc. of Taylor polynomials.
For that, I can use the numpy functions. Numpy is apparently smart enough to call the member function sin(self) of my class afloat when it realizes that the argument of numpy.sin is not a known type.
This is really great. However, some functions are not as smart: Among them trace inv dot
As a workaround, i could this:
def inv(X): if X.__class__ == afloat: return X.inv() else: return numpy.linalg.inv(X)
This is somewhat OK, but I'd like to use already existing Python code that uses Numpy internally. So I have to rely that numpy.inv(X) calls X.inv() when X is object of my class.
best regards, Sebastian