python - 在Python中绘制牛顿法

标签 python newtons-method

在下面的代码中,我用 Python 实现了牛顿法。

import math
def Newton(f, dfdx, x, eps):
    f_value = f(x)
    iteration_counter = 0
    while abs(f_value) > eps and iteration_counter < 100:
        try:
            x = x - float(f_value)/dfdx(x)
        except ZeroDivisionError:
            print ("Error! - derivative zero for x = ", x)
            sys.exit(1)     # Abort with error
        f_value = f(x)
        iteration_counter += 1

    # Here, either a solution is found, or too many iterations
    if abs(f_value) > eps:
        iteration_counter = -1
    return x, iteration_counter
def f(x):
    return (math.cos(x)-math.sin(x))
def dfdx(x):
    return (-math.sin(x)-math.cos(x))
solution, no_iterations = Newton(f, dfdx, x=1, eps=1.0e-14)
if no_iterations > 0:    # Solution found
    print ("Number of function calls: %d" % (1 + 2*no_iterations))
    print ("A solution is: %f" % (solution))
else:
    print ("Solution not found!")

但是现在我希望在同一时间间隔上绘制收敛图。这将是作为迭代次数函数的绝对误差。

我尝试创建一个迭代器,每次都会生成一个具有绝对误差和迭代的二元组。下面是我的代码,还包括我从中得到的错误,

import math
def Newton(f, dfdx, x, eps):
    f_value = f(x)
    iteration_counter = 0
    while abs(f_value) > eps and iteration_counter < 100:
        try:
            x = x - float(f_value)/dfdx(x)
            yield interation_counter, abs(f(x))
        except ZeroDivisionError:
            print ("Error! - derivative zero for x = ", x)
            sys.exit(1)     # Abort with error
        f_value = f(x)
        iteration_counter += 1

    # Here, either a solution is found, or too many iterations
    if abs(f_value) > eps:
        iteration_counter = -1
def f(x):
    (math.cos(x)-math.sin(x))
def dfdx(x):
    (-math.sin(x)-math.cos(x))

通过这个,我尝试将结果放入数组中,以便我可以绘制结果

import numpy as np
np.array(list(Newton(f,dfdx, 1,10e-4)))

但是我收到以下错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-20-9378f4e2dbe3> in <module>()
      1 import numpy as np
----> 2 np.array(list(Newton(f,dfdx, 1,10e-4)))

<ipython-input-19-40b67c2c3121> in Newton(f, dfdx, x, eps)
      4     f_value = f(x)
      5     iteration_counter = 0
----> 6     while abs(f_value) > eps and iteration_counter < 100:
      7         try:
      8             x = x - float(f_value)/dfdx(x)

TypeError: bad operand type for abs(): 'NoneType'

最佳答案

我建议将每次迭代的每个值 x 和相应的输出 f 存储在两个各自的数组中,然后返回每个数组。如果你的函数是正确的(你应该知道它是否收敛),那么这应该很容易做到。从那里,只需绘制数组即可。

我几个月前就这么做了。你可以在这里看到我是如何完成它的: How to tell if Newtons-Method Fails

这里有几点需要注意。

1)我没有检查以确保您的函数是否正确收敛。

2) 牛顿法通常具有非常大的步长,并且您通常不会获得其收敛的任何漂亮的可视化效果。 <10 次迭代的情况并不少见,而且它们通常也不遵循到达收敛点的平滑路径(再次强调,步长较大)。请注意,对于我实现的代码,只有 3 次迭代。但这可能只是因为你的功能是错误的。坦白说,我不确定

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

def Newton(f, dfdx, x, eps):
    xstore=[]
    fstore=[]
    f_value = f(x)
    iteration_counter = 0
    while abs(f_value) > eps and iteration_counter < 100:
        try:
            x = x - float(f_value)/dfdx(x)
        except ZeroDivisionError:
            print ("Error! - derivative zero for x = ", x)
            sys.exit(1)     # Abort with error
        f_value = f(x)
        xstore.append(x)
        fstore.append(f_value)
        iteration_counter += 1

    # Here, either a solution is found, or too many iterations
    if abs(f_value) > eps:
        iteration_counter = -1

    return x, iteration_counter,xstore,fstore

def f(x):
    return (math.cos(x)-math.sin(x))
def dfdx(x):
    return (-math.sin(x)-math.cos(x))

solution, no_iterations,xvalues,fvalues = Newton(f, dfdx, x=1, eps=1.0e-14)

if no_iterations > 0:    # Solution found
    print ("Number of function calls: %d" % (1 + 2*no_iterations))
    print ("A solution is: %f" % (solution))
else:
    print ("Solution not found!")

x = np.array([i for i in xvalues])
f = np.array(fvalues)
fig = plt.figure()
plt.scatter(x,f,label='Newton')
plt.legend()

enter image description here

关于python - 在Python中绘制牛顿法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53145336/

相关文章:

python - 如何从字典中删除重复值?

c++ - 无限循环计算立方根

python - 如何判断牛顿法是否失败

python - 我可以遍历python中的逻辑运算符吗?

python - 无需安装即可使用/导入 Beautiful Soup 4

python - ModuleNotFoundError : No module named 'com.aspose'

python - 如何组织使用 Curl 返回的数组?

java - java上牛顿法实例讲解

assembly - 使用Newton-Raphson方法在x87 FPU上建立多维数据集根

c - 牛顿收敛法不起作用