分数运算

从python 2.6开始已包含fraction这个模块
python 2.5可以用这个模块玩玩看
http://svn.python.org/view/python/branches/release25-maint/Demo/classes/Rat.py?view=markup&pathrev=51333
#
gcd=lambda a,b:a if b==0 else gcd(b,a%b)
class F:
        def __init__(self,fenzi,fenmu=1):
              while fenzi!=int(fenzi) or fenmu!=int(fenmu) : fenzi*=10;fenmu*=10
              g=gcd(fenzi,fenmu)
              self.fenzi=int(fenzi//g)
              self.fenmu=int(fenmu//g)
        def __str__(self):
              return str(self.fenzi)+'/'+str(self.fenmu)
        
        def __add__(self,other):
              fenzi=self.fenzi*other.fenmu+other.fenzi*self.fenmu
              fenmu=self.fenmu*other.fenmu
              g=gcd(fenzi,fenmu)
              return F(fenzi//g,fenmu//g)
        def __neg__(self):
               return F(-self.fenzi,self.fenmu)
        def __sub__(self,other):
               return self+(-other)
        def __mul__(self,other):
               fenzi=self.fenzi*other.fenzi
               fenmu=self.fenmu*other.fenmu
               g=gcd(fenzi,fenmu)
               return F(fenzi//g,fenmu//g)
        def __invert__(self):
               return F(self.fenmu,self.fenzi)
        def __div__(self,other):
               return self*(~other)

while True:print eval(raw_input('eval:'))

支持分数的加(+)减(-)乘(*)除(/),取倒数(~)
支持小数化分数.

示例:eval:F(2.8,22)
输出结果为7/55

你可能感兴趣的:(SVN,python,F#)