Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在达到公差数后停止代码(用于函数近似)_Python_Python 3.x_Math_Numeric_Numerical Methods - Fatal编程技术网

Python 如何在达到公差数后停止代码(用于函数近似)

Python 如何在达到公差数后停止代码(用于函数近似),python,python-3.x,math,numeric,numerical-methods,Python,Python 3.x,Math,Numeric,Numerical Methods,因此,我有以下代码: import numpy as np def g_of_x(x): return ((5/x**2)+3) initial_guess = 3 for i in range(15): solution = g_of_x(initial_guess) initial_guess = solution iterations = i + 1 print('iteration: %d, solution: %f' % (iteration

因此,我有以下代码:

import numpy as np

def g_of_x(x):
    return ((5/x**2)+3)

initial_guess = 3
for i in range(15):
    solution = g_of_x(initial_guess)
    initial_guess = solution
    iterations = i + 1
    print('iteration: %d, solution: %f' % (iterations, solution))
代码将函数值近似于区间[3,5]上的实解。如果我需要实现10^^(-5)的容差,这样当代码达到该容差级别时就会停止,那么该如何实现呢


在这段代码中,第10次迭代的值是正确的答案,我希望我的代码在达到该值时停止。

因此,下面是我使用@Dexter0411 suggestion找到的解决方案:

initial_guess = 3
previous_solution = 3
iterations = 0
while True:
    solution = g_of_x(previous_solution)
    if math.isclose(previous_solution,solution,abs_tol=math.pow(10,-5)) == True:
        previous_solution = solution
        iterations += 1
        print('iteration: %d, solution: %.10f' % (iterations, previous_solution))
        break
    else:
        previous_solution = solution
        iterations += 1
        print('iteration: %d, solution: %.10f' % (iterations, previous_solution))

因为最后一个输出将是在公差范围内的输出。

那么,您将如何在纸面上进行此操作?是什么阻止了您在代码中实现该逻辑?在纸面上还是在视觉上,当我看到小数点后的第5位随着程序运行更多的迭代而固定时,我知道该值是第一个达到该公差水平的值。查找
break
(和
continue
以获取完整性)以,打破循环。@VoltStatic你不知道如何在Python中实现吗?你可以使用cmath.isclose(a,b,abs_tol=math.pow(10,-5))…首先复制初始猜测。但是我理解你的担心,第五个值在迭代之后会被修正。。