I am trying to write a program in Python which approximates a real number by a fraction up to precision 10^-3. Here is what I did, I don't know what's wrong. Can someone help me ? I use the "clockwork addition". Can someone tell me what's wrong with it ? thanks in advance.
from math import *
def restriction(x,a,b,c,d):
if x<(a+b)/(c+d):
return [x,a,b,a+c,b+d]
if x>(a+b)/(c+d):
return [x,a+c,b+d,c,d]
def cancres(x,a,b,c,d,prec):
if x==a/b or x==c/d:
return x
elif x<a/b or x>c/d:
return False
else:
w=restriction(x,a,b,c,d)
i=0
if (w[3]/w[4]-w[2]/w[1])>prec:
w=restriction(x,w[1],w[2],w[3],w[4])
print w
i+=1
return w
print cancres(sqrt(3),3,2,2,1,10^(-3))