Я создаю функцию, которая многократно тестирует другую функцию, чтобы получить значение в пределах заданного пользователем допуска. Я пытался заставить его печатать сообщение об ошибке в случае, когда требуется больше итераций, чтобы попасть в заданный допуск, но это сообщение никогда не печатается, и я не могу понять, почему.
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)
Вот что я написал. Заданное значение n в последней строке является наименьшим значением, для которого ctrap работает должным образом. Есть идеи?
Не сравнивайте числа с
is
. Используйте==
.@ Аран-Фей, спасибо!