I'm making a function that's repeatedly testing another function in order to get a value within a user-provided tolerance. I've tried to make it print an error-message in the case where more iterations are needed to get within the given tolerance, but this message never prints and I can't figure out why.
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)
This is what I've written. The given n-value in the final line is the lowest value ctrap works properly for. Any ideas?
is
. Use==
.