I have attempted to change my code several times to create an array of the required values of S.
import math as math
def trap(f,a,b):
return ( f(a) f(b) ) / 2 * (b-a)
a = 0
b = 2
n_vals = [2**p for p in range (0,21)]
h_vals = [(b-a)/n for n in n_vals]
f= lambda x: math.exp(x) x**2
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}")
Is there a way to produce a list that reads
I = [12.38905609893065, 9.91280987792437, 9.271610109481282, ...]
CodePudding user response:
What are the "required" values? If it's all of them, you can initialize a list and append to it.
import math as math
def trap(f,a,b):
return ( f(a) f(b) ) / 2 * (b-a)
a = 0
b = 2
n_vals = [2**p for p in range (0,21)]
h_vals = [(b-a)/n for n in n_vals]
f= lambda x: math.exp(x) x**2
output = []
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}")
output.append(S)
print(output)