class - how to convert a float to a fraction in python? -
this question has answer here:
- how convert floats human-readable fractions? 25 answers
i trying define class fraction:
def __init__(self,num=0,denom=1): self.num = num self.denom = denom
and want define add method,
def __add__(self,right): if type(right) int: return (self.num/self.denom) + right if type(right) fraction: return ((self.num/self.denom)+(right.num/right.denom)) def __radd__(self,left): return (self.num/self.denom)+left
it works, , returns float. however, want return fraction. example: if test:
f = frac(1,2) f + frac(1,3) f + 2 frac(1,3) + f 2 + f
i get:
*error: f+frac(1,3) -> 0.8333333333333333 should -> 5/6 *error: f+2 -> 2.5 should -> 5/2 *error: frac(1,3)+f -> 0.8333333333333333 should -> 5/6 *error: 2+f -> 2.5 should -> 5/2
are there methods can convert result float fraction? thank much.
don't create float in first place. example,
def __add__(self,right): if type(right) int: return fraction(self.num + right*self.denom, self.denom) elif if type(right) fraction: # reducing answer lowest terms left # exercise reader return fraction(self.num*right.denom + right.num*self.denom, self.denom*right.denom)
Comments
Post a Comment