You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python梯形法积分程序报错:trapezoidal()位置参数数量不匹配求解

问题原因
  • 你的trapezoidal函数仅定义了3个位置参数x0/xn/n,但你用*n_interval解包列表传参时,如果输入的elements≥2,列表就会有≥2个元素,解包后传入trapezoidal的参数总数就会超过3,触发参数数量不匹配的错误。
  • 额外隐藏bug:你先执行a = lower_limit、b = upper_limit赋值,再接收用户输入的上下限,会直接抛出变量未定义的错误,需要调整代码顺序。
修改方案

保留列表作为参数传入的逻辑,根据你的实际需求选择以下两种方案即可:

方案1:适配多组子区间数对比误差的需求(符合你代码里绘图的原始设计)

直接修改trapezoidal函数接收子区间列表,批量计算所有子区间数对应的结果:

  1. 修改梯形法函数定义
# 调整后支持传入子区间列表,返回所有N对应的积分结果
def trapezoidal(x0,xn,n_list):
    res_list = []
    for n in n_list:
        # 计算步长
        h = (xn - x0) / n
        integration = f(x0) + f(xn)
        for i in range(1,n):
            k = x0 + i*h
            integration = integration + 2 * f(k)
        integration = integration * h/2
        res_list.append(integration)
    return res_list
  1. 调整精确积分代码的位置,放在用户输入上下限之后
# Input section
lower_limit = float(input("Enter lower limit of integration: "))
upper_limit = float(input("Enter upper limit of integration: "))
elements = int(input("Enter number of elements : "))

#Sub_interval list
n_interval = []
for val in range(0, elements):
    sub_interval = int(input("Enter number of sub intervals: "))
    n_interval.append(sub_interval)

# 把精确积分的计算移到这里,避免变量未定义错误
I = ply.polyint(polynom())
a = lower_limit
b = upper_limit
A = ply.polyval(b, I) - ply.polyval(a, I)
  1. 调整调用、输出和绘图逻辑
# 不需要解包,直接传入列表
result_list = trapezoidal(lower_limit, upper_limit, n_interval)
error_list = [((res - A)/A)*100 for res in result_list]

print("Indefinite integral's constant of exact integration is: ", I)
print("Definite integral of the exact integration is: ", A)
for n, res, err in zip(n_interval, result_list, error_list):
    print(f"子区间数={n}时,梯形法积分结果:{res},误差百分比:{err}%")

# 绘图调整
plt.plot(n_interval, error_list, marker='o')
plt.title("Comparison of 'N' to Error Values" )
plt.xlabel("N value")
plt.ylabel("Error value(%)")
plt.show()

方案2:仅需计算一组子区间数的结果

不需要修改函数定义,仅调整调用逻辑,取列表内的指定元素(比如最后一个输入的子区间数)传入即可:

# 不需要解包,直接取列表的对应元素作为n传入
result = trapezoidal(lower_limit, upper_limit, n_interval[-1])

同时记得把精确积分的代码移到用户输入上下限之后,修复变量未定义的问题。

内容的提问来源于stack exchange,提问作者nurhadidd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 14:57:04