* If you are doing intro2cs in huji be careful... I know why you're here *
I'm trying to build a function that get a function (assume continuity of monotone) as argument and return its inverse function.
From mathematics I know that I need to reflect the function to y=x
.
but this isn't going very well.
I wrote something that will give me the x0
that makes f(x0)=0
.
def solve(f, x0=-10000, x1=10000, epsilon=EPSILON):
"""return the solution to f in the range between x0 and x1"""
while x1-x0>EPSILON:
if (f(x0)*f((x1+x0)/2))<0:
x1=((x1+x0)/2)
elif (f(x0)*f((x1+x0)/2))>0:
x0=((x1+x0)/2)
elif (f(x0)*f(x1))==0:
if f(x0)==0:
return x0
else:
return x1
if f(x0)*f(x1)<0:
return (x1+x0)/2
else:
return None
The problem is that I don't know what will be the range's input on the function. I think I need to work on small range at first, and if I won't find a solution i'll expand the range exponentially.
Any ideas?
UPDATE:
ok so I tried to write it as @Spektre
suggested and I succeed:
def inverse(g, epsilon=EPSILON):
"""return f s.t. f(g(x)) = x"""
def helper(y):
x0=-2
x1=2
while x1<10000:
if solve((lambda x:g(x)-y),x0,x1,epsilon):
return solve((lambda x:g(x)-y),x0,x1,epsilon)
else:
x0=math.pow(x0,3)
x1=math.pow(x1,3)
return helper