Determine if python fraction can have equivalent decimal

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.

+4
source share
2 answers

Using this:

If the denominator has any prime factors other than 2 and 5, then it does not have an exact decimal representation. - Helwood

You can verify this by dividing 2s and then 5s, and then checking if the result is 1:

def has_decimal_representaion(frac):
    d = frac.denominator
    for n in (2, 5):
        while d % n == 0:
            d = d / n
    return d == 1
+8

Fraction(1, 3) == float(1/3) , float(1/3) , - . , 6004799503160661/18014398509481984:

>>> (1/3).as_integer_ratio()
(6004799503160661, 18014398509481984)

, , .

, , , 2 5, SymPy factorint limit, . , fraction.Fraction sympy.Rational , .

def is_representable(rational):
    d = sympy.Rational(rational).q
    return not bool(set(sympy.factorint(d, limit=10).keys()) - {2, 5})
+1

Source: https://habr.com/ru/post/1668596/


All Articles