I am trying to evaluate an integral using the trapezoidal rule for a range of n = 2^p where p= [1,2...20], to produce different values for the integral. I have tried to implement a for loop to define n and h however I get a TypeError:'list' object cannot be interpreted as an integer. Is there a way to adjust my code to produce my desired outcome?
import math as math
#define limits of our interval
a=0
b=2
#define our n value
n_vals=[2**p for p in range (0,21)]
#define our h value
h_vals=[(b-a)/n for n in n_vals]
#define our function f(x) here
f= lambda x: math.exp(x) x**2
#we calculate the trapezium method by breaking it into smaller parts
#We use for loop calculating integral of f(x) using trapezium rule
#Combine parts to find integral
S = 0.5*(f(a) f(b))
for k in range(1,n_vals):
S = f(a k*h_vals)
Integral = h_vals*S
print("Integral = %f" % Integral)
CodePudding user response:
Here you have some problems, first you need to iterate over an index or over the desired nvals to calculate de integral every time I will make you a proposal of solution, but I think your method it's bad defined because that's not how you calculate an integral
import math as math
#define limits of our interval
a=0
b=2
#define our n value
n_vals=[2**p for p in range (0,21)]
#define our h value
h_vals=[(b-a)/n for n in n_vals]
#define our function f(x) here
f= lambda x: math.exp(x) x**2
#we calculate the trapezium method by breaking it into smaller parts
#We use for loop calculating integral of f(x) using trapezium rule
#Combine parts to find integral
for n,h in zip(n_vals,h_vals): #here n and h are the actual value for every iteration
S = 0.5*(f(a) f(b))
for k in range(1,n):
S = f(a k*h) #here you have a problem with definition of trapezoidal integral
Integral = h*S
print(f"Integral = {Integral}")
another proposal is to create a function that calculate the integral for an interval and then acumulate calling that function:
def trap(f,a,b):
return ( f(a) f(b) ) / 2 * (b-a)
import math as math
#define limits of our interval
a=0
b=2
#define our n value
n_vals=[2**p for p in range (0,21)]
#define our h value
h_vals=[(b-a)/n for n in n_vals]
#define our function f(x) here
f= lambda x: math.exp(x) x**2
and now your integration code:
for n,h in zip(n_vals,h_vals):
S = 0
for k in range(n):
thisA = a k*h
thisB = a (k 1)*h
S = trap(f,thisA,thisB)
print(f"Integral for {n} partitions = {S}")