Python 在不打印自述错误消息的情况下中断函数
我正在做一个函数,它反复测试另一个函数,以获得用户提供的公差范围内的值。我试图让它在需要更多的迭代才能在给定的公差范围内打印错误消息,但这个消息从未打印,我不知道为什么Python 在不打印自述错误消息的情况下中断函数,python,Python,我正在做一个函数,它反复测试另一个函数,以获得用户提供的公差范围内的值。我试图让它在需要更多的迭代才能在给定的公差范围内打印错误消息,但这个消息从未打印,我不知道为什么 from math import e def ctrapezoidal(f,a,b,n): h=((b-a)/n) y = (h/2)*(f(a)+f(b)) for x in range(n-1): p = a + ((x+1)/n)*(b-a) y = y + h*(
from math import e
def ctrapezoidal(f,a,b,n):
h=((b-a)/n)
y = (h/2)*(f(a)+f(b))
for x in range(n-1):
p = a + ((x+1)/n)*(b-a)
y = y + h*(f(p))
return y
def ctrap(f,a,b,n,tol):
for x in range(n):
if x is 0:
continue
elif x is 1:
continue
elif x is (n-1):
if abs((ctrapezoidal(f,a,b,x)) - (ctrapezoidal(f,a,b,(x-1)))) < tol:
print("The integral of the function between",a,"and",b,"approximates to",ctrapezoidal(f,a,b,x),"with a tolerance of",tol)
break
else:
print("The approximation needs more iterations to calculate the integral to the given tolerance.")
#This error never shows, even when given too few iterations to compute.
#The if-statement works, though, since I've tried with values
#of n one integer higher than the needed number of iterations.
else:
if abs((ctrapezoidal(f,a,b,x)) - (ctrapezoidal(f,a,b,(x-1)))) < tol:
print("The integral of the function between",a,"and",b,"approximates to",ctrapezoidal(f,a,b,x),"with a tolerance of",tol,". This calculation took",x,"iterations.")
break
else:
continue
def g(x):
y = 2*e**(2*x) + 2*x
return y
ctrap(g,1,5,1331,1.e-4)
从数学导入e
def Ctrapezoid(f、a、b、n):
h=((b-a)/n)
y=(h/2)*(f(a)+f(b))
对于范围(n-1)内的x:
p=a+((x+1)/n)*(b-a)
y=y+h*(f(p))
返回y
def ctrap(f、a、b、n、tol):
对于范围(n)内的x:
如果x为0:
持续
elif x为1:
持续
elif x为(n-1):
如果abs((ctrapezoidal(f,a,b,x))-(ctrapezoidal(f,a,b,(x-1)))
这是我写的。最后一行中给定的n值是ctrap正常工作的最低值。
有什么想法吗?问题出在线路上
elif x is (n-1):
当您使用is
进行比较时,Python会测试左侧和右侧,以查看它们是否表示完全相同的对象。例如,它可能会比较它们的内存地址。但通常,具有相同数值的两个整数不会是同一个对象。您可以通过启动解释器并运行
>>> 1331 is (1330 + 1)
False
这表明在代码中写入1331
时得到的整数对象与写入1330+1
时得到的整数对象不同,即使它们具有相同的数值。这就是为什么你的比较失败的原因;您有不同的对象表示同一个整数,您正在测试对象相等性,而不是数字相等性
使用==
测试数值相等性
>>> 1331 == (1330 + 1)
True
请注意,Python的标准实现会缓存多达256个整数对象,因此每个值只有一个实例。因此,最大为256的整数也将比较对象相等:
>>> 256 is (255 + 1)
True
>>> 257 is (256 + 1)
False
不过,您不应该依赖于此。不要将数字与
is
进行比较。使用==
@aranfey谢谢!