Python 使用列表计算积分梯形规则
我想从头开始写一个梯形法则的公式。我对python还不太熟悉,所以我正在进行一些尝试。我想整合一个表达式,我把它写成了一个名为square的列表 我已经在写积分了:Python 使用列表计算积分梯形规则,python,list,integral,numerical-integration,Python,List,Integral,Numerical Integration,我想从头开始写一个梯形法则的公式。我对python还不太熟悉,所以我正在进行一些尝试。我想整合一个表达式,我把它写成了一个名为square的列表 我已经在写积分了: square = [] #Create empty list for i in range(0, len(dos)): square.append(dos[i]*dist[i]) #Multiplication from inside the integral s1 = 0
square = [] #Create empty list
for i in range(0, len(dos)):
square.append(dos[i]*dist[i]) #Multiplication from inside the integral
s1 = 0
s2 = 0
for i in square[i] != square[1] and square[-1]:
s1 += s1 + 0.01 * square[i]
else:
s2 += s2 + 0.01 * 0.5 * square[i]
print(s1,s2)
我得到了以下错误:
for i in square[i] != square[1] and square[-1]:
TypeError: 'float' object is not iterable
有人知道代码有什么问题吗
提前谢谢 您需要
for
循环和if
语句,然后您还使用了+=
,因此您不需要在右操作数中添加s1
,因为这将添加它两次
# equivalent
s1 += square[i]
s1 = s1 + square[i]
使用tome提示获取更清晰的代码
创建zip
列表,在square
和dos
列表上迭代dist
- 在
上按元素迭代,而不是按其索引square
- 在中使用
,而不是双重条件
你能解释一下你想在
中为方[i]中的i做什么吗!=square[1]和square[-1]:
您想迭代并设置一个条件,它看起来是的,我想说的是,如果列表square上的元素I与第一个和最后一个元素都不同,那么它计算的和为s1
s1 = 0
s2 = 0
for i in range(len(square)):
if square[i] != square[0] and square[i] != square[-1]:
s1 += 0.01 * square[i]
else:
s2 += 0.01 * 0.5 * square[i]
square = [do * di for do, di in zip(dos, dist)]
s1 = 0
s2 = 0
for elt in square:
if elt not in (square[0], square[-1]):
s1 += 0.01 * elt
else:
s2 += 0.01 * 0.5 * elt