Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pure Python rational numbers module for 2.5

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

like image 501
Constantin Avatar asked Nov 30 '08 20:11

Constantin


3 Answers

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

like image 105
A. Coady Avatar answered Sep 28 '22 07:09

A. Coady


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.

like image 32
Robert Gamble Avatar answered Sep 28 '22 06:09

Robert Gamble


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.

like image 30
Constantin Avatar answered Sep 28 '22 06:09

Constantin