如何使Python在For循环中的第n次迭代中打印某些内容



我想在回答我的问题之前说,我对Python非常陌生,只是在研究生院的某个特定课程中才开始使用它。

我已经编写了一个脚本,使用迭代方法(如不动点、二分法和Newton-Raphson方法(来查找函数的根。我的算法的python代码如下:

定点法:

def fixedpoint(func, g_func,x0,tol, MAXIT):

def g(x):
return eval(g_func)

print(f"Seeking root of {func}.")
print("FIXED POINT ITERATION:")
iterated_x = g(x0)
for i in range(0, MAXIT):
iterated_x = g(iterated_x)
print("Iteration", i + 1, iterated_x)
condition = abs(g(iterated_x) - (iterated_x)) 
if condition < tol:
print(f"The root converges to {iterated_x} after {i+1} iterations.")
break
if i == MAXIT and condition >= tol:
print("ERROR: The root did not converge after maximum iterations.")
fixedpoint('x**2 - 4*x + 2', '(x**2+2)/4', 0.75, 10**(-4), 100)
fixedpoint('math.exp(-x) + x - 7 ', '7 - math.exp(-x)', 0.75, 10**(-4), 100)

二等分法:

def bisection(func,a, b, tol, MAXIT):

def f(x):
return eval(func)

print(f"Seeking root of {func}")
print("BISECTION METHOD:")
if f(a)*f(b) <0:
for i in range(0, MAXIT):
c = (a+b)/2
if f(a)*f(c) < 0:
a = a
b = c
print(f"Iteration", i + 1, f(c))
elif f(b)*f(c) < 0:
b = b
a = c
print(f"Iteration", i + 1, f(c))
if f(c) == 0 or abs(f(c)) < tol:
print ("Exact Solution Found")
print(f"Iteration", i + 1, c)
print("The root converges to", c, "after", i + 1, "iterations.")
break
elif i == MAXIT and abs(f(c)) > tol:
print("Bisection method fails.")

return None
bisection('x**2 - 4*x + 2',0.5, 1, 10**(-4), 100)
bisection('math.exp(-x) + x - 7',6, 8, 10**(-4), 100)

Newton-Raphson方法:

def newtonraphson(func, deriv, x0, tol, MAXIT):

def f(x):
return eval(func)
def ddx(x):
return eval(deriv)


print(f"Seeking root of {func}.")
print("NEWTON-RAPHSON METHOD:")

for i in range(1, MAXIT):
iterated_x = x0 - (f(x0)/ddx(x0))
x0 = iterated_x
print(f"Iteration", i, x0)
if f(x0) < tol:
print(f"The root converges to {x0} after {i} iterations.")
break
elif i==MAXIT and f(x0) > tol:
print("After maximum iterations, root was not found.")
newtonraphson('x**2-4*x+2', '2*x-4', 0.75,10**(-4), 100)
newtonraphson('math.exp(-x) + x - 7', '-(math.exp(-x)) + 1', 0.75,10**(-4), 100)

虽然我的脚本能够成功地找到我感兴趣的方程的根,但我遇到了一个更简单的问题。基本上,我想告诉我的程序,如果在最大迭代之后,我的容差条件没有满足,那么打印";方法失败";。

然而,当我对最大迭代次数设置为100并且容差设置为0.0001时不覆盖的函数进行实验时,我的代码并没有打印出我想要的语句。

失败打印语句的语法正确吗?

做诸如";如果i==MAXIT并且f(x0(>tol";在我写的函数的上下文中有意义吗?

我将感谢所有关于这个问题的建议,因为我正在努力改进Python。

谢谢。

在Python中实现这一点的一个好方法是使用forelse构造。从本质上讲,如果你挂了一个";否则";子句,如果循环由于break语句而没有提前终止,它将执行。这对于正在搜索某些内容的循环非常有用,而根查找绝对符合这种模式。所以你的定点迭代循环看起来像:

for i in range(0, MAXIT):
iterated_x = g(iterated_x)
condition = abs(g(iterated_x) - (iterated_x)) 
if condition < tol:
print(f"The root converges to {iterated_x} after {i+1} iterations.")
break
else:
print("ERROR: The root did not converge after maximum iterations.")

这样做的一个好处是,如果您在循环中更改成功标准,那也没关系——如果您不使用break语句声明成功,那么无论成功是如何定义的,else子句都会运行。

您面临的问题是python中的range只从开始索引到结束索引之前的一个索引起作用。也就是说,range(0,3)遍历数字(0,1,2(。在代码中发生的情况是,您根本无法激活失败条件,因为索引从未真正达到该值。然而,修复很容易。在你的函数中,你说:

for i in range(1,MAXIT):
if f(x0) < tol:
print(f"The root converges to {x0} after {i} iterations.")
break
elif i==MAXIT and f(x0) > tol:
print("After maximum iterations, root was not found.")

只需将其替换为

for i in range(1,MAXIT):
if f(x0) < tol:
print(f"The root converges to {x0} after {i} iterations.")
return
print("After maximum iterations, root was not found.")

相反。这样做的目的是,如果函数找到了解决方案,就停止它;如果你在没有找到答案的情况下完成了整个循环,就给你错误消息。

最新更新