Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using numpy vector elements in Fraction module in Python

I'm trying to use elements from a numpy array as an input for the Fraction module and I'm getting the following error: "TypeError: both arguments should be Rational instances"

For example, if I do:

Y  =  np.array([7,1], dtype='int64')  
X  =  Y[0]*3+Y[1]

And then:

a = Fraction(58,X)  

I'll get the same error. I also tried to do X=X.astype('int'), or X=X.astype('int32'), without success.

What do I have to do to convert the numpy array in a "Rational instance" that is needed for Fraction module?

like image 514
gabriel_papaiz Avatar asked Apr 22 '13 12:04

gabriel_papaiz


1 Answers

This seems to be one of the unfortunate artifacts of the way Numpy integers interact with Python's abstract classes (and it's also dependent on whether you run a 32-bit or 64-bit Python, because dtype='int' means either np.int32 or np.int64, but never Python int).

Explicitly converting to Python int should work:

Fraction(58, int(X))
like image 144
Fred Foo Avatar answered Sep 27 '22 20:09

Fred Foo