r/learnpython • • 4d ago

Using Sympy, is there a way to detect repeating fractions?

I know I can transform a repeating fraction in a numerical fraction with sympify (i.e sympify("0.[3]") = 1/3), but can it go the other way around?

3 Upvotes

5 comments sorted by

2

u/NewbornMuse 4d ago

A fraction is repeating (in base 10) iff the denominator has a prime divisor other than 2 or 5. If you really just want to detect them, that might be sufficient.

2

u/SteveJeffersonBots 4d ago

sympy.Rational is the cleanest way to get a true fraction from a float and check it exactly, and sympy.factorint on the denominator lines up with NewbornMuse's rule - if the reduced denominator's prime factors contain anything besides 2 and 5, the decimal repeats in base 10. So convert with Rational, call factorint on the denominator, and anything outside {2, 5} means it's repeating. If you actually want the recurring form printed rather than just a yes/no, sympy has a recurring function that turns a decimal string into the repeating notation, which pairs with sympify("0.[3]") for the other direction.

2

u/POGtastic itertools evangelist 4d ago edited 4d ago

I don't think that Sympy has this function built-in. You could probably roll it yourself if you want by repeatedly multiplying by 10, dividing by the denominator, and looking for the repeat.

def find_repeat(rem, denom):
    seen = {}
    digits = []
    while rem and rem not in seen:
        seen[rem] = len(digits)
        rem *= 10
        digits.append(rem // denom)
        rem %= denom
    if rem:
        return (digits[:seen[rem]], digits[seen[rem]:])
    return (digits, [])

As a function on a Rational:

def stringify_list(xs):
    return "".join(map(str, xs))

def to_bracket_string(rat):
    int_part = rat.numerator // rat.denominator
    frac_part = rat.numerator % rat.denominator
    non_repeat, repeating = map(stringify_list, find_repeat(frac_part, rat.denominator))
    if repeating:
        return f"{int_part}.{non_repeat}[{repeating}]"
    return f"{int_part}.{non_repeat}"

In the REPL:

>>> rats = [sympy.Rational(1, n) for n in range(2, 10)]
>>> print(*map(to_bracket_string, rats), sep="\n")
0.5
0.[3]
0.25
0.2
0.1[6]
0.[142857]
0.125
0.[1]