Pythonで有理数クラスを作ってみた。
class cRational:
def __init__(self, a, b = 1):
self.a = a
self.b = b
self.normalize()
def __add__(self, r):
if isinstance(r, cRational):
return cRational(self.a * r.b + self.b * r.a, self.b * r.b)
else:
return cRational(self.a + self.b * r, self.b)
def __sub__(self, r):
if isinstance(r, cRational):
return cRational(self.a * r.b - self.b * r.a, self.b * r.b)
else:
return cRational(self.a - self.b * r, self.b)
def __mul__(self, r):
if isinstance(r, cRational):
return cRational(self.a * r.a, self.b * r.b)
else:
return cRational(self.a * r, self.b)
def __div__(self, r):
if isinstance(r, cRational):
return cRational(self.a * r.b, self.b * r.a)
else:
return cRational(self.a, self.b * r)
def __radd__(self, r):
return cRational(r * self.b + self.a, self.b)
def __rsub__(self, r):
return cRational(r * self.b - self.a, self.b)
def __rmul__(self, r):
return cRational(r * self.a, self.b)
def __rdiv__(self, r):
return cRational(r * self.b, self.a)
def normalize(self):
if self.b < 0:
self.a = -self.a
self.b = -self.b
a = abs(self.a)
b = self.b
div = b
while a % b > 0:
a %= b
if b % a == 0:
div = a
break
b %= a
div = b
self.a /= div
self.b /= div
def __str__(self):
if self.b == 1:
return str(self.a)
else:
return str(self.a) + "/" + str(self.b)
a = cRational(1, 6)
b = cRational(1, 3)
print 3 + a