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

Michael S. Gilbert michael.s.gilbert@gmail....
Mon Apr 27 16:25:19 CDT 2009


On 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)
> 
> fails, so I have to move the division into the inner list, which leads
> to  a lot of duplicate typing and general messiness:
> 
> >>>> 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.
> 
> >>>> def zeros( nsamples ):
> >>>>    list = []
> >>>>    for n in range( nsamples ):
> >>>>        list.append( fractions.Fraction( 0 ) ) 
> >>>>    return numpy.array( list )
> 
> is a solution, but it would be nice to have this built-in, e.g.:
> 
> >>>> numpy.zeros( n , dtype=numpy.fraction )
> 
> Perhaps developing a fraction dtype would solve the above poly1d issue
> as well?  Anyway, just some thoughts to ponder.

It also seems that numpy's basic math operations do not work with
fractions:

>>> math.sin(fractions.Fraction(1,2))
0.47942553860420301
>>> numpy.sin(fractions.Fraction(1,2))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: sin
>>> numpy.exp(fractions.Fraction(1,2))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: exp

Mike


More information about the Numpy-discussion mailing list