|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
你还在为浮点运算不精确而 吗?
你还在因为0.0000000001 == 0而 吗?
没关系!
- def gcd(a, b):
- if b == 0:
- return a
- return gcd(b, a % b)
- def tongfen(c, m):
- f = gcd(c, m)
- return c // f, m // f
- class fen:
- def __init__(self, child, mother):
- if mother < 0:
- mother = abs(mother)
- child = 0 - child
- self.c, self.m = tongfen(abs(child), mother)
- self.c *= (child < 0) * -2 + 1
- if self.m == 0:
- raise ValueError("chu'shu'bu'neng'wei'ling")
- def __invert__(self):
- return fen(0 - self.c, self.m)
- def __add__(self, other):
- return fen(self.c * other.m + other.c * self.m, self.m * other.m)
- def __sub__(self, other):
- return self + (~other)
- def __mul__(self, other):
- return fen(self.c * other.c, self.m * other.m)
- def __truediv__(self, other):
- return fen(self.c * other.m, self.m * other.c)
- def __repr__(self):
- if self.m == 1:
- return str(self.c)
- elif self.c < self.m:
- return "%d/%d"%(self.c, self.m)
- else:
- return "%d+%d/%d"%(self.c//self.m, self.c%self.m, self.m)
- def __eq__(self, other):
- return self.c == other.c and self.m == other.m
复制代码
|
|