对于赋值,我们被要求创建一个返回逆函数的函数。基本问题是从平方函数创建平方根函数。我提出了一个使用二进制搜索的解决方案和另一个使用牛顿方法的解决方案。我的解决方案对于立方根和平方根似乎很有效,但对于log10则不行。以下是我的解决方案:#Binary Search
def inverse1(f, delta=1e-8):
"""Given a function y = f(x) that is a monotonically increasing function on
non-negative numbers, return the function x = f_1(y) that is an approximate
inverse, picking the closest value to the inverse, within delta."""
def f_1(y):
low, high = 0, float(y)
last, mid = 0, high/2
while abs(mid-last) > delta:
if f(mid) < y:
low = mid
else:
high = mid
last, mid = mid, (low + high)/2
return mid
return f_1
#Newton's Method
def inverse(f, delta=1e-5):
"""Given a function y = f(x) that is a monotonically increasing function on
non-negative numbers, return the function x = f_1(y) that is an approximate
inverse, picking the closest value to the inverse, within delta."""
def derivative(func): return lambda y: (func(y+delta) - func(y)) / delta
def root(y): return lambda x: f(x) - y
def newton(y, iters=15):
guess = float(y)/2
rootfunc = root(y)
derifunc = derivative(rootfunc)
for _ in range(iters):
guess = guess - (rootfunc(guess)/derifunc(guess))
return guess
return newton
无论使用哪种方法,当我在教授的测试函数中得到log10()的输入n=10000时,我都会得到这个错误:(异常:当使用牛顿的方法函数时,log10()是很远的,而这种二进制搜索方法在达到输入阈值之前是相对准确的,不管是哪