log10 反函数 c语言,单调递增函数的逆函数,log10()的溢出错误

对于赋值,我们被要求创建一个返回逆函数的函数。基本问题是从平方函数创建平方根函数。我提出了一个使用二进制搜索的解决方案和另一个使用牛顿方法的解决方案。我的解决方案对于立方根和平方根似乎很有效,但对于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()是很远的,而这种二进制搜索方法在达到输入阈值之前是相对准确的,不管是哪

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值