改进牛顿法递归

-3 投票
2 回答
4101 浏览
提问于 2025-04-17 06:21

我之前解决了一个问题,现在遇到了这个新的问题,感觉有点卡住了。这个问题要求我改进我之前发布的解决方案,但我不太明白具体要改进什么。(而且我也不知道该怎么解决。)请帮帮我,谢谢。

问题描述:
Elena抱怨说,在项目2中的递归牛顿函数里,有一个多余的参数是用来估算的。使用这个函数的人在调用时不应该需要提供这个值,因为这个值总是一样的。请修改这个函数的定义,让它使用一个关键字参数,并为这个参数设置一个合适的默认值。然后调用这个函数时不传第二个参数,以证明这样可以解决这个问题。

这是我的代码:

def newtonSquare(x, estimate):
    if abs(x-estimate ** 2) <= 0.000001:
        return estimate
    else:
        return newtonSquare(x, (estimate + x / estimate) / 2)

def main():
    num = int(raw_input('Enter a positive number >> '))
    print newtonSquare(num, 1.0)

main()

2 个回答

0

迈克尔的默认值解决方案还有一个替代方法,就是把递归函数定义在newtonSquare函数里面:

def newtonSquare(x):

    def f(x, estimate):
        if abs(x-estimate ** 2) <= 0.000001:
            return estimate
        else:
            return f(x, (estimate + x / estimate) / 2)

    return f(x, 1.0)

def main():
    num = int(raw_input('Enter a positive number >> '))
    print newtonSquare(num)

main()

不过在这种情况下,使用默认值会更好一些,更灵活一些,但这个方法依然是个有用的模式。

2

这个问题是有人抱怨,当他们调用 newtonSquare 这个函数时,总是用1.0作为初始估计值。为了把这个值设置为默认值,除非你明确提供其他值,否则你只需要修改这个函数的定义,变成下面这样:

def newtonSquare(x, estimate = 1.0):

撰写回答