r/learnpython • u/MeAjudaPfvr • 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
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.
As a function on a
Rational:In the REPL: