I was given a task to find a way to make a function to turn floats into fractions as accurate as possible, and by sheer brute forcing, i created a function like this
def isclose(a, b, tolerance):
return abs(a-b) <= tolerance
def fraction(a, factor=0, tol=0.01):
while True:
factor += 1
a_rounded = int(round(a*factor))
if isclose(a*factor, a_rounded, tol):
break
if factor == 1:
return a_rounded
else:
return "{}/{}".format(a_rounded, factor)
Is there a more efficient way to do it, without having to rely on external modules? I can't use modules, as I'm trying to implement this to micropython, which doesn't have the fractions library.