The Incomplete Works of Josh English

Writings and Ramblings about almost anything...

Fraction.py

I was working on a Polynomial Root Solver and got very tired of looking at Python spit out long decimal representations of numbers, thus messing up my formatted text columns. I wanted to look at them as fractions, so instead. I did a search through the Vaults of Parnassus and found a fraction.py module by Mike Hostetler. One thing led to another as I updated his code and I ended up writing a fairly robust fraction class that did the tricks I needed plus a lot more.

Download fraction here

The Fraction class of fraction.py is fairly powerful. It can add, subtract, multiply, and divide itself with integers, floats, and other fractions. A fraction can be raised to a power (but only integer powers at this point). It can even convert a decimal to a fraction with startling accuracy. Here are some examples.


>>> from fraction import Fraction
>>> f=Fraction(1,2)
>>> g=Fraction(3.5)
>>> f,g
(1/2, 7/2)

The decimal to fraction conversion is very handy.


>>> f+g
4
>>> f-g
-3
>>> f*g
7/4
>>> f/g
1/7

The Fraction class lets you use fractions the same way you use integers or float values.


>>> f+2.5
3
>>> g-2.5
1
>>> 

The Fraction class also lets you display the fraction in various ways:


>>> g.toDecimal()
3.5
>>> g.mixedNumber()
'3 1/2'
>>> g.tuple()
(7, 2)
>>> g.mixedTuple()
(3, 1, 2)

The Fraction class reduces to the simplest form of itself on command.


>>> h=Fraction(315,400)
>>> h.reduce()
>>> h
63/80