不动点迭代算法
我被要求写一个程序来解决这个方程 ( x^3 + x - 1 = 0 ),使用的是固定点迭代的方法。
什么是固定点迭代的算法? 有没有Python的固定点迭代代码示例?(不是模块里的函数,而是包含算法的代码)
谢谢你
2 个回答
0
伪代码可以在这里找到,你可以从那里了解它的内容。
1
首先,看看这个:
我选择了牛顿法。
如果你想了解生成器函数,可以这样定义一个生成器函数,并创建一个生成器对象:
def newtons_method(n):
n = float(n) #Force float arithmetic
nPlusOne = n - (pow(n,3) + n - 1)/(3*pow(n,2) +1)
while 1:
yield nPlusOne
n = nPlusOne
nPlusOne = n - (pow(n,3) + n - 1)/(3*pow(n,2) +1)
approxAnswer = newtons_method(1.0) #1.0 can be any initial guess...
然后你可以通过调用来获得越来越好的近似值:
approxAnswer.next()
想了解更多关于生成器的信息,可以查看:PEP 255 或者 类(生成器) - Python v2.7
例如:
approx1 = approxAnswer.next()
approx2 = approxAnswer.next()
或者更好的是,使用循环!
至于什么时候你的近似值足够好……;)