#!/usr/bin/env python
VERBOSE=False
class Rational:
zaehler = 1
nenner = 1
ggt = 1
def __init__(self,z,n):
if (not type(n) == type(1)) or (not type(z) == type(1)):
raise TypeError, 'Numerator and Denominator have to be integers!'
if n == 0:
raise DivisionByZero, 'Denominator is Zero!'
if n < 0:
print 'Warning: Denominator shall be a positive integer'
print ' You entered: %d' % n
n *= -1
z *= -1
self.zaehler = z
self.nenner = n
self.simplify()
def find_ggt(self):
"Find the greatest common denominator"
for i in range(min(abs(self.zaehler),abs(self.nenner)),1,-1):
if (not self.zaehler%i and not self.nenner%i):
if VERBOSE: print "GGT gefunden:", i
self.ggt = i
return i
else:
if VERBOSE: print "Kein GGT gefunden"
return None
def simplify(self):
"Simplify/reduce the fraction"
if self.ggt == 1:
self.find_ggt()
if self.ggt != 1:
self.zaehler /= self.ggt
self.nenner /= self.ggt
return str(self)
def floatify(self):
"Return a float"
return self.zaehler/float(self.nenner)
def __add__(self,other):
return Rational(
self.zaehler*other.nenner + other.zaehler*self.nenner,
self.nenner*other.nenner
)
def __mul__(self,other):
return Rational(
self.zaehler*other.zaehler,
self.nenner*other.nenner
)
def __str__(self):
if self.zaehler == 0:
return "%d" % 0
if self.nenner == 1:
return "%d" % self.zaehler
return "%d / %d" % (self.zaehler,self.nenner)
if __name__ == '__main__':
r = Rational(-49,7)
s = Rational(-2,12)
t,u = r+s,r*s
print r, r.floatify()
print u,u.floatify()
print t,t.floatify()