从 for 循环创建列表

Creating a list from a for loop

我曾多次尝试更改我的代码以创建所需 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}")

有没有办法生成包含 S 值序列的列表:

I = [12.38905609893065, 9.91280987792437, 9.271610109481282, ...]


您可以初始化一个列表并在外循环的每次迭代中附加到它:

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)