【问题标题】:Fixed point iteration in PythonPython中的定点迭代
【发布时间】:2020-07-20 23:50:40
【问题描述】:

我是 Python 初学者,但我对这项任务有疑问:

  • 编写一个使用定点迭代查找用户数学函数根的函数。
  • 使用此函数查找以下的根:x^3 + x - 1
  • 绘制根近似与迭代算法步数的关系图。

这是我第一次使用 Python,所以我真的需要帮助。这是我的代码,但它不起作用:

import math
import matplotlib.pyplot as plt
import numpy as np

def fixedp (function, x0, min = 0.001, max = 100):
  i = 0
  e = 1
  xp = []
  while (e > min and i < max):
    x = function(x0)
    e = norm(x0 - x)
    x0 = x
    xp.append(x0)
    i = i + 1
  return x, xp

fx = input("Wrote function : ")
function = lambda x: eval(fx)

x_start = 0.5
xf,xp = fixedp(function, x_start)

x = linspace(0,2,100)
y = function(x)
plot(x, y, xp, function(xp), 'bo', x_start, f(x_start), 'ro', xf, f(xf), 'go', x, x, 'k')
show()

【问题讨论】:

  • 为什么它不起作用?你调试过吗?也许给我们一个输入和预期输出?
  • i = 0 IndentationError: expected an indented block.我不知道怎么解决
  • 这是因为在此之后您没有:。我建议使用一些文本编辑器来帮助您识别此类错误。 Pycharm、Noteped++ 或 Sublime 都很棒
  • 你也应该知道具体x^3 + x - 1不会收敛。
  • 我知道,但我不知道该怎么办。我在一段时间后写了:,但i = 0也有同样的错误

标签: python algorithm math iteration fixed-point-iteration


【解决方案1】:

首先,我会注意到您的代码的逻辑很棒并且可以正常工作。缩进和语法有一些问题,所以我重写了你的代码。

import matplotlib.pyplot as plt
import numpy as np
from typing import Tuple, List
from math import *


def iteration(given_function, x0, min_error=0.001, max_iteration=3) -> Tuple[float, List]:
    i = 0
    error = 1
    xp = []
    x = None
    while error > min_error and i < max_iteration:
        x = given_function(x0)
        error = abs(x0 - x)
        x0 = x
        xp.append(x0)
        i += 1
    print(xp)
    return x, xp


def plot(xf, xp, x_start, given_function):
    function_v = np.vectorize(given_function)

    x = np.linspace(0, 2, 100)
    y = function_v(x)
    plt.plot(x, y)
    plt.plot(xp, function_v(xp), 'bo')
    plt.plot(x_start, given_function(x_start), 'ro')
    plt.plot(xf, given_function(xf), 'go')
    plt.plot(x, x, 'k')
    plt.show()


def main():
    fx = input("Write function: ")
    given_function = lambda x: eval(fx)

    x_start = 0.9
    xf, xp = iteration(given_function, x_start)

    plot(xf, xp, x_start, given_function)


if __name__ == '__main__':
    main()

祝你以后在 Python 上好运!

【讨论】:

  • 非常感谢!现在它正在工作,我理解我的错误! :)
【解决方案2】:

好的,Yonlif 的代码可以正常工作,但我尝试输入:

next_function = 'x ** 3 + x - 1'

    x_start = 0.9
    xf, xp = iteration(next_function, x_start)

    plot(xf, xp, x_start, next_function)

进入主函数但它不起作用我不明白为什么

【讨论】:

  • 这是因为x^3 + x - 1 不收敛。
  • 另外,您不应该每次需要回复时都发布答案:)
【解决方案3】:

我有这样的错误:

11     x = None
     12     while error > min_error and i < max_iteration:
---> 13         x = given_function(x0)
     14         error = abs(x0 - x)
     15         x0 = x

TypeError: 'str' object is not callable

【讨论】:

  • 这仍然相关吗?如果不是,请删除此答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-15
  • 2022-01-21
  • 2015-04-03
  • 1970-01-01
相关资源
最近更新 更多