我正在嘗試使用梯形規則對 n = 2^p 范圍內的積分進行評估,其中 p= [1,2...20],以生成不同的積分值。我試圖實作一個 for 回圈來定義 n 和 h 但是我得到一個 TypeError:'list' object cannot be interpret as an integer。有沒有辦法調整我的代碼以產生我想要的結果?
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)
uj5u.com熱心網友回復:
在這里你有一些問題,首先你需要迭代一個索引或所需的 nval 來計算 de 積分每次我會給你一個解決方案的建議,但我認為你的方法定義不好,因為這不是你計算積分的方式
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}")
另一個建議是創建一個函式來計算一個區間的積分,然后累積呼叫該函式:
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
現在您的集成代碼:
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}")
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/335730.html
