【问题标题】:Evaluate integrals trapezoid rule using lists使用列表评估积分梯形规则
【发布时间】:2021-07-12 18:29:06
【问题描述】:

我正在尝试从头开始编写梯形规则的公式。我对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
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 i in square[i] != square[1] and square[-1]: 中做什么,你想迭代并设置一个看起来像的条件
  • 是的,我想说的是,如果列表正方形上的元素 i 与第一个和最后一个元素都不同,那么它会将总和计算为 s1

标签: python list integral numerical-integration


【解决方案1】:

你需要for循环然后if语句,你也使用+=所以你不需要在右边的操作数中添加s1,因为那会添加两次

# equivalent
s1 += square[i]
s1 = s1 + square[i]
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]

拥有使代码更简洁的技巧

  • zip 创建 square 列表,在 dosdist 列表上进行迭代
  • square 上迭代不是其索引上的元素
  • 使用in 代替双重条件
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

【讨论】:

    猜你喜欢
    • 2015-06-21
    • 2020-06-02
    • 2015-05-15
    • 1970-01-01
    • 1970-01-01
    • 2015-02-13
    • 1970-01-01
    • 1970-01-01
    • 2020-05-07
    相关资源
    最近更新 更多