简体   繁体   English

Python中的图形图

[英]Graphing diagram In Python

In the following code I have implemented Newtons method in Python. 在以下代码中,我已在Python中实现了Newtons方法。

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!")

However now I am looking to plot the convergence diagram on that same interval. 但是,现在我希望在同一时间间隔上绘制收敛图。 This would be the absolute error as a function of the number of iterations on the interval [0,1]. 这将是绝对误差,它是间隔[0,1]上迭代次数的函数。 Meaning the number of iterations on the x axis with the corresponding absolute error on the y axis 表示在x轴上的迭代次数,在y轴上具有相应的绝对误差

I attempted to make an iterable that each time yields a 2-tuple with the absolute error, and the iteration. 我试图使每次迭代产生一个带有绝对错误和迭代的2元组。 Here is my code below, with the output and graph. 这是我下面的代码,以及输出和图形。 Is my output correct? 我的输出正确吗? should the graph look like this? 该图应该看起来像这样吗? All help is greatly appreciated! 非常感谢所有帮助! The number of iterations from my code is 3 我的代码中的迭代次数为3

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 iteration_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
    return x, iteration_counter
def f(x):
    return (math.cos(x)-math.sin(x))
def dfdx(x):
    return (-math.sin(x)-math.cos(x))

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

which produces the following output: 产生以下输出:

array([[0.00000000e+00, 4.74646213e-03],
   [1.00000000e+00, 1.78222779e-08]])

and finally: 最后:

import numpy as np
import matplotlib.pyplot as plt

data = np.array(list(Newton(f,dfdx, 1, 10e-14)))
plt.plot(data[:,0], data[:,1])
plt.yscale('log')
plt.show()

which produces the graph: 产生图:

在此处输入图片说明

  1. Your Newton function shouldn't yield and return at the same time 您的Newton函数不应同时屈服并返回
  2. Use a more slowly converging function to test your results 使用更慢的收敛函数来测试结果

This is what I would do: 这就是我要做的:

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


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 iteration_counter, x, 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

def f(x):
    return x ** 2 - 1.34

def dfdx(x):
    return 2 * x

data = np.array(list(newton(f, dfdx, 10, 10e-14)))

# plt.plot(data[:, 0], data[:, 1]) # x-axis: iteration, y-axis: x values
plt.plot(data[:, 0], data[:, 2]) # x-axis: iteration, y-axis: f(x) values
plt.yscale('log')
plt.show()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM