# [Numpy-discussion] Some minor issues with numpy and fractions

Pauli Virtanen pav@iki...
Mon Apr 27 16:24:02 CDT 2009

```Mon, 27 Apr 2009 17:04:17 -0400, Michael S. Gilbert wrote:

> I had mentioned recently some interest in using fractions in the numpy
> polynomial class. Suprisingly, it actually works for the most part out
> of the box, which is great. However, there are some minor issues.  For
> example:
>
> >>> numpy.poly1d( [ fractions.Fraction(1,2) , fractions.Fraction(1, 8) ]
> ...             )/fractions.Fraction(3,4)

Polydiv can probably be fixed to handle this, it doesn't appear to be
duck-typing clean in this case.

> > >>> numpy.poly1d( [ fractions.Fraction(1,2)/fractions.Fraction(3,4) ,
> > >>> fractions.Fraction(1,8)/fractions.Fraction(3,4) ] )
>
> Another item of general interest for numpy is that there is no simple
> way to allocate memory for fraction array.

Something similar came up a while ago. You can do this:

>>> a = np.frompyfunc(Fraction, 1, 1)(np.zeros((50, 50), int))

and so

>>> a[0,0] += Fraction(1, 3)
>>> a /= 7
>>> a
array([[1/21, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
...,
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0]], dtype=object)

The trick is to create an universal function out of the object
constructor, and feed it initializer data. Works for any classes.

I'm undecided whether it'd be a good idea to add a specialized routine
for doing this...

--
Pauli Virtanen

```

More information about the Numpy-discussion mailing list