I need to write a python function that takes an object of the "Fraction" class as an argument and determines whether the fraction can be represented in decimal format. For example, 1/2 can be represented in 0.5, but 1/3 does not have a decimal equivalent with a finite number of digits (0.333333333 is an approximate value).
My approach was to compare the fraction with the numerator divided by the denominator as follows (suppose the "frac" is a Fraction object):
if frac == frac.numerator / frac.denominator:
print('has decimal representaion')
else:
print('has no decimal representation')
but in many cases this does not work. For example, Python allows comparison Fraction(347, 1000) == 0.347, it returns False, although it should be True. I know that python has a problem related to floating point operations, so I'm looking for a workaround or package that solves this problem.
Note. I used sympy, but in sympy, the comparison S(1)/3 == 1/3returns Truewhere I need it to be False.
source
share