7

Has anybody seen such a thing? Small self-sufficient modules are preferred.

Constantin
  • 27,478
  • 10
  • 60
  • 79

3 Answers3

10

The fractions module from 2.6 can be ripped out if necessary. Grab fractions.py, numbers.py, and abc.py; all pure python modules.

You can get the single files from here (2.6 branch, 2.7 does not work): http://hg.python.org/cpython/branches

guettli
  • 25,042
  • 81
  • 346
  • 663
A. Coady
  • 54,452
  • 8
  • 34
  • 40
  • True, i thought it would be much more difficult! – Constantin Dec 01 '08 at 00:36
  • Note: This doesn't appear to work in the general case. E.g: fractions.Fraction(10) * 10 => Attribute Error: 'int' object has no attribute 'numerator'. int objects seem to have a numerator in Python 2.6, but not in Python 2.5. I'd be interested to know how others worked around this problem (I forced my literals to be fractions before using operators). – benno May 16 '12 at 22:32
  • A better work-around is to change the definitions of 'forward' and 'reverse' in the '_operator_fallbacks' function to correctly handle int, and long. Hard to described in the comment due to limited format options, but something like: "elif isinstance(b, (int, long)): return monomorphic_operator(a, Fraction(b)" – benno May 16 '12 at 22:41
9

SymPy is a symbolic maths library written entirely in Python and has full support for rational numbers. From the tutorial:

>>> from sympy import *
>>> a = Rational(1,2)

>>> a
1/2

>>> a*2
1

>>> Rational(2)**50/Rational(10)**50
1/88817841970012523233890533447265625

There is also GMP for Python (GMPY) which, while not pure Python, is probably more efficient.

Robert Gamble
  • 106,424
  • 25
  • 145
  • 137
3

One more thing to try is Rat.py from demo folder in Python 2.5 maintenance branch. If i understand correctly, it is the daddy of 2.6 fractions. It's a single module without dependencies.

>>> from Rat import rat
>>> rat(1) / rat(3)
Rat(1,3)
>>> rat(1, 3) ** 2
Rat(1,9)

UPDATE: Nah, fractions.py is about 2.5 times faster for my task.

Constantin
  • 27,478
  • 10
  • 60
  • 79