【问题标题】:Solve this equation with fixed point iteration method in python [closed]在python中用定点迭代法求解这个方程[关闭]
【发布时间】:2019-09-14 23:54:47
【问题描述】:
f(x) = x^2- 2x - 3 = 0

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

【问题讨论】:

标签: python numerical-methods equation nonlinear-functions fixed-point-iteration


【解决方案1】:

定点迭代

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)

【讨论】:

    【解决方案2】:

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

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

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

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

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

    【讨论】:

    • 强制使用定点法。
    【解决方案3】:

    一个可能的迭代是

    f(x) = 2 + 3 / x.
    

    导数是

    f'(x) = - 3 / x²
    

    这样迭代将收敛于x² &gt; 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
    

    请注意,在这两种情况下,分子每次都减一,而分母则定期增加。

    【讨论】:

      猜你喜欢
      • 2015-12-29
      • 2012-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多