*如果你在huji做介绍,请小心。。。 我知道你为什么来这里*
我试图建立一个函数,得到一个函数(假设单调的连续性)作为参数并返回它的逆函数。
从数学上我知道我需要将函数映射到y=x
。
但这不是很顺利。
我写了一些东西,可以给我x0
这个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
问题是我不知道函数的输入范围是什么。 我想我首先需要处理小范围的问题,如果找不到解决方案,我会以指数方式扩展范围。
有什么想法吗?
更新:
好吧,我试着按照@Spektre
的建议来写,我成功了:
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
目前没有回答
相关问题 更多 >
编程相关推荐