在python中用定点迭代方法求解这个方程


f(x) = x^2- 2x - 3 = 0

如何求解这个方程非线性,并在Python中使用定点迭代方法?

定点迭代

f(x( = x^2-2x-3 = 0 ⇒ x(x-2( = 3

⇒ x = 3/(x-2(

import math
def g(x):
if 2 == x:
return x + 1e-10
return 3/(x-2)
def quadratic(ff,x=0):
while abs(x-ff(x)) > 1e-10:
x = ff(x);
return x
print(quadratic(g))

-1

寻根公式

# -*- coding:utf8 -*-
import math
def quadratic(a, b, c):
''' ax² + bx + c = 0
return
True  : all real number
Fasle :  no solutions
(x1,x2)
'''
if not isinstance(a, (int, float)):
raise TypeError('a is not a number')
if not isinstance(b, (int, float)):
raise TypeErrot('b is not a number')
if not isinstance(c, (int, float)):
raise TypeError('c is not a number')
derta = b * b - 4 * a * c
if a == 0:
if b == 0:
if c == 0:
return True
else:
return False
else:
x1 = -c / b
x2 = x1
return x1, x2
else:
if derta < 0:
return False
else:
x1 = (-b + math.sqrt(derta)) / (2 * a)
x2 = (-b - math.sqrt(derta)) / (2 * a)
return x1, x2
print(quadratic(1, -2, -3))

(3.0, -1.0(

这是一个二次方程,您可以使用闭式表达式(即无需使用定点迭代(求解,如下所示。

在这种情况下,您将有两个解决方案:

x1 = -(p/2) + math.sqrt((p/2)**2-q)
x2 = -(p/2) - math.sqrt((p/2)**2-q)

其中 p 是第一个系数(示例中为-2(,q 是第二个系数(示例中为 -3(。

对于一般情况,您必须检查 sqrt 运算符中的表达式是否大于或等于零。如果它小于零,则方程将没有实数解。如果它等于零,则两个解相等(称为双根(。

可能的迭代是

f(x) = 2 + 3 / x.

导数为

f'(x) = - 3 / x²

以便迭代将收敛x² > 3.

2开始,迭代是

2, 7/2, 20/7, 61/20, 182/61, 547/182... -> 3

这不适用于另一个根(负值(,因为负值很快就会变成正值。

@tinyhare使用的公式,

f(x) = 3 / (x - 2)

有导数

f'(x) = - 3 / (x - 2)²

并且肯定会停留并收敛负面。

-2, -3/4, -12/11, -33/34, -102/101, -303/304, ... -> -1

请注意,在这两种情况下,分子每次都偏离 1,而分母有规律地增加。

最新更新